Thursday, December 2, 2010

How to Add Custom Navigation Menus to Your Themes

menus-compassWordPress 3.0 comes with support for custom navigation menu. The new feature is a good way for you to add navigation menu to your theme with little configuration. Best of all, it allows you to administer the menus from your dashboard. No longer do you need to tamper with the code to add/remove items from the menus.

Now, unless you are using an updated theme, chances are, your old theme does not support this new custom navigation menu feature. Here is how you can modify your current theme to support the menus feature.

Registering custom menus


Before you can use the menus, you have to first decide how many navigation menus you need, then register them with WordPress.

Open up the functions.php file in your theme folder and insert in the following code:

[php]add_action( 'after_setup_theme', 'register_my_menus' );
function register_my_menus() {
register_nav_menus( array(
'top-nav' => __( 'Top-Level Navigation Menu' ),
'footer-nav' => __( 'Footer Navigation Menu' ),
) );
}[/php]

The above code will register two menus for your theme, one for the top-level menu and another for the footer menu. You can add as many menus as you like.

Setting up the menus


Next, login to your WordPress dashboard and go to "Appearance -> Menus". Under the "Theme Locations", you should see the two navigation menus that you have added just now.

menus-location

You can now proceed to create your menu items.

1. Enter a name for your new menu. Once done, click the "Save Menu" button.

menus-new-menu

2. On the left, check the boxes beside the pages/categories that you want to add and click the "Add to menu" button (you can also create custom links if you want to point to an external site). Drag and drop the entry to arrange them in the order you want. Click "Save Menu" again.

3. Under the menu location, click on the dropdown bar to select your newly created menu. Click Save.

menus-create-menu

Displaying the menu on your site


In the location where you want the menu to appear (most probably in the header.php file), insert in the following code:

[php]<?php
if(function_exists('wp_nav_menu')) {
wp_nav_menu(array(
'theme_location' => 'top-nav',
'menu_class' => 'topnav_menu',
'fallback_cb' => 'false',
));
}
?>[/php]

The above code will display the "top-nav" menu in an unordered list with the class "topnav_menu". You can then style it up in your stylesheet. Note that I have set the "fallback_cb" to be "false", which means that nothing will appear if the top-nav is not configured in the backend. Alternatively, you can define your own function to display an alternative menu if the default is not present.

That's it. For more information, check out the WordPress codex.

Image credit: Calsidyrose

No comments:

Post a Comment