• SumoMe
No. Not that menu.

Today I will share to you a very simple solution on how you can show different custom menus that corresponds to specific pages in WordPress 3.

Since WordPress 3 was released, it came with the handy feature of creating custom menus from the admin panel. Both default themes – Twenty Ten and Twenty Eleven supports this feature. For those who are still new to it, it can be accessed in Appearance > Menus. From here you can create new menus and manage existing ones.

There is a WordPress function that we need that allows you to display a custom menu in your theme. This is the wp_nav_menu(). For this tutorial I will leave it at that but if you want to familiarize yourself further with this function please click here. (A WordPress developer knows that there is no better resource to learn more about WordPress than the Codex. 🙂 )

With that we can begin with the “clever” part:
(skip here if you already know the stuff above)

When you want a menu to appear in a particular page, simply use the slug of that page as the menu name.

Most of you would have already predicted how the rest should work by now. Using the function wp_nav_menu in your template file, you only have to supply the page name in the function as argument for the menu name. Consider the following function:

function show_menu_for_current_page() {
	global $wp_query;
	$post_obj = $wp_query->get_queried_object();
	$page = get_page($post_obj->ID);

	$menu_name = $page->post_name;

	wp_nav_menu( array(
		'menu' => $menu_name
		));
}

When this function is used in your page template (assuming it is already written in your functions.php file), it displays the custom menu with the same name as the current page.

In my case, I used this to display a menu of sub-pages of a given page. Before anything else, I created custom menus consisting of sub-pages of their corresponding parent page. I named each menu to the parent page respectively. Every time a page OR one of its sub-pages is visited, it displays the menu of that family of pages (up to the parent) only. By modifying the code above by a parameter we can achieve this:

function show_menu_for_current_page() {
	global $wp_query;
	$post_obj = $wp_query->get_queried_object();
	$page = get_page($post_obj->post_parent);

	$menu_name = $page->post_name;

	wp_nav_menu( array(
		'menu' => $menu_name
		));
}

The only thing that changed here is Line 4. Instead of getting the immediate page ($post_obj->ID) I fetched the parent page ($post_obj->post_parent) so that the same menu still displays when the sub-pages are navigated.

I hope this little tutorial have been some help. Cheers!

Image credit: hisks