Control WordPress Nav Menu via Custom Fields


WordPress 3.0 also includes the menus, in addition to a number of other new features. Normally you generate a menu automatically by creating pages, but under Appereance / Menus you can create your own menu and assign a place where it replaces the normal menu.

But whoever currently uses WordPress as a CMS and blog (like me) may now have a problem: If you look at the blog you should be able to see the normal pages in the navigation, but if you then select a page with many subpages it would be nice if the subpages were listed in the menu bar as well as listing only one entry "Blog" which brings you back to the blog page.

Conveniently, WordPress already includes everything you need to put together this idea. They are on the one hand of course the aforementioned menus, and on the other side there are Custom Fields. If you have not hidden, you can find at every post and every page an editor where you can enter meta data. Via this meta data and with the help of a small code snippet you can control what is displayed in the menu.

You can put the code snippet in your functions.php of your Theme or in a Plugin.

//Filter the arguments for the wp_nav_menu_function to include a custom menu on pages.
function nr_2010_wp_nav_menu_args($args = '')
{
	if ( is_page() ) //custom menus only on sites
	{
		global $post;

		$menu_name = get_post_meta($post->ID, 'menu_name', true);

		if( !empty($menu_name) && is_nav_menu($menu_name) )
		{
			$args['menu'] = $menu_name;
		}
	}
	return $args;
}
add_filter( 'wp_nav_menu_args', 'nr_2010_wp_nav_menu_args' );

This code puts a filter on wp_nav_menu_args, these are the parameters of the function wp_nav_menu, which the Theme uses to output the menus.

As long as we are on a page (is_page()) the custom field menu_name will be used. If it's not empty and it has a menu with this name, the paramaters of this call will be modified, so it shows the right menu.

Only one thing left: Provide the correct meta data to the pages and create the corresponding menus. The menu editor is very intuitive, it shouldn't be a problem. Just a hint: It doesn't save automatically. 😉

Guest Post

This post was written by Niklas Rother - niklas-rother.de and is a post in our Advent Calendar Series on WP Engineer about WordPress.
Thank you very much from my part to Niklas.
If you also like to have your interesting post published on our website, please let us know on our contact page. Of course we will appreciate your contribution!