Categories: Wordpress

wp_nav_menu() and WordPress 3

WordPress 3 comes with a new very useful feature, menus.

Themes can now use the built-in menu instead of using 100 different solutions. Still, sometimes its better to use 3rd party solution for menu, but let’s leave that alone..

The other day, I was playing around with this function (wp_nav_menu()) and came to a weird problem. At least it looked like that. Actually it looked like a bug.

The problem or the bug was that the DIV’s ID and structure was different.

Here’s an example of the DIV and UL when the menu is set.

<div class="menu-header"><ul class="menu" id="menu-test">

And here’s if the menu is not set.

<div class="menu"><ul>

As you can see, the class “menu” jumped from UL to DIV. That of course results in menu being broken because CSS is not set right anymore.

This looked like a bug, until I read the function reference again. (Yes, I missed something..)

Let me explain, as I’ve seen a few¬†people asking about this.

If you use wp_nav_menu() in your theme and the menu is not created yet in the admin area of WP, wp_nav_menu() will fallback to the old menu function called wp_page_menu().

Now, if you do not want that, define your own fallback function like I do, and tell the user to create a menu straight away when they install your theme.

Here’s an example of the fallback function for the menu.

function fallback_no_menu()
{
	$menu = '<div class="menu-header"><ul class="menu"><li class="menu-item menu-item-type-post_type"><a href="'.get_bloginfo('url').'/wp-admin/nav-menus.php">Configure the menu by clicking here</a></li></ul></div>';

	echo $menu;
}

And you set this function in the wp_nav_menu like:

wp_nav_menu(array('container_class' => 'menu-header', 'theme_location'  => 'primary', 'fallback_cb' => 'fallback_no_menu'));

This will show the “Configure the menu by clicking here” text in the menu and if the user clicks on it, it will take them to the WP admin area, the menus page.

Much better solution if you ask me then just showing the old menu.

2 Comments

  1. This one made me crazy :) In Twenty Eleven I was not able to hook into wp_nav_menu_items filter until I found this gem of yours. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *