How to add support for navigation menus to your WordPress theme
The new navigation menus system in WordPress 3.0 looks promising, but in my opinion it's not very usable yet. Anyway, here's one way to add navigation menus to your theme while maintaining backward compatibility:
In your theme's functions.php add something like the following code:
<?php
function mytheme_addmenus() {
register_nav_menus(
array(
'main_nav' => 'The Main Menu',
)
);
}
add_action( 'init', 'mytheme_addmenus' );
function mytheme_nav() {
if ( function_exists( 'wp_nav_menu' ) )
wp_nav_menu( 'menu=main_nav&container_class=pagemenu&fallback_cb=mytheme_nav_fallback' );
else
mytheme_nav_fallback();
}
function mytheme_nav_fallback() {
wp_page_menu( 'show_home=Start&menu_class=pagemenu' );
}
?>
In line 1 we add support for the navigation menus. The mytheme_nav() function is what you will use in the theme to display the menu. Inside that function we check if wp_nav_menu() exists, that means if we're running WordPress 3.0 (or later). If not we'll use the fallback function mytheme_nav_fallback().
Notice that the fallback also gets called if no navigation menus have been created in the admin area. That's what the fallback_cb parameter on line 4 does.To keep the HTM markup and the CSS consistent you'll have to use the container_class parameter on wp_nav_menu but the menu_class parameter for wp_page_menu.In your template use the following code to use your new custom function:
<?php mytheme_nav(); ?>
Resources
Ramblings
What's good about the new menu system:- Total control over what appears in the menu
- You can add posts, pages, categories and tags in the menu
- Very nice drag and drop interface
- You will have to teach your users how to use the system properly.
- If you create new pages they won't be added to your existing menu (except for top level pages).
- You can not control your page menus through the navigation menus interface. I think it is... very very odd that WordPress doesn't have a simple drag-and-drop interface to arrange pages.
- The previous point means that the new menu system is useless unless you update your theme.
- The
wp_nav_menu()call is inconsistent with the existingwp_page_menu()function.
I am Nicolas Kuttler, a web developer, system administrator and IT consultant from France, currently living in Germany.
28 comments
Start a new thread