Tag Archives: wp_nav_menu

Breadcrumbs based on WordPress menus

Here’s a quick and dirty function for generating breadcrumbs based on pages in a WordPress menu. Please note that I have not tested this with menu items based on post types other than pages.

function jki_get_nav_menu_id_for_post($post_id)
{
	$items = wp_get_nav_menu_items('Huvudmeny');
	
	$menu_item_id = -1;
	
	// Find menu item
	foreach ((array)$items as $menu_item) {
		if($menu_item->object_id == $post_id) {
			$menu_item_id = $menu_item->ID;
			break;
		}
	}
	
	return $menu_item_id;
}

function jki_get_nav_menu_item($item_id)
{
	$args = array( 'post_type' => 'nav_menu_item', 
	    'post_status' => 'publish', 
	    'output' => ARRAY_A, 
	    'p' => $item_id);
	
	$query = new WP_Query($args);
	$items = $query->get_posts();
	$items = array_map( 'wp_setup_nav_menu_item', $items );
	
	if(count($items) > 0) {
		return $items[0];
	}	
	else {
		return null;
	}
}

function jki_wp_menu_breadcrumbs()
{	
	global $post;

	$menu_item_id = jki_get_nav_menu_id_for_post($post->ID);
	
	if($menu_item_id == -1) return;
	
	$current_menu_item = jki_get_nav_menu_item($menu_item_id);
	
	if($current_menu_item == null) return;
	
	$delimiter = '<span> // </span>';
	$crumbs = array();
	
	$crumbs[] = $delimiter . $current_menu_item->title;
	
	if($current_menu_item->menu_item_parent != 0) {
		$is_top = false;
		while($is_top == false) {
			$current_menu_item = jki_get_nav_menu_item($current_menu_item->menu_item_parent);
			$crumbs[] = $delimiter . '<a href="' . $current_menu_item->url . '">' . $current_menu_item->title . '</a>';
			
			if($current_menu_item->menu_item_parent == 0) {
				$is_top = true;
			}
		}
	}
	
	$crumbs = array_reverse($crumbs);
	
	echo "<div id=\"breadcrumbs\">\n";
	echo '<a href="/">Home</a>';
	foreach ($crumbs as $crumb) {
		echo $crumb;
	}
	echo "\n</div>\n";
}