Navigation Menus in WordPress

Posted on Posted in My Blog

Navigation Menus

Navigation Menus in WordPress allow you to add custom navigation menus into your theme. This is a great alternative to wp_list_pages for creating your site navigation. In order to setup menus in your theme, you need to add a few lines of code to your theme files.

Edits to functions.php

First, in your theme’s functions.php file, you need to write a function that registers your menu. As an example, this menu would appear in the “Theme Locations” box as “Header Menu”.

function register_my_menus() {
    array('header-menu' => __( 'Header Menu' ) )

Then you need to ensure that the theme turns these menu options on, so you need this bit of code as well:

add_action( 'init', 'register_my_menus' );

The above tells the theme to run your “register_my_menus” procedure. As you can see, your new function makes use of the WordPress register_nav_menus functionality.

Now add the menu to your template files

Add the following code any place in your theme template files that you want the menu to show up . The code to use here is wp_nav_menu:

<?php wp_nav_menu( array( 'theme_location' => 'header-menu' ) ); ?>

Back to the Menus Panel

To finish, you would simply visit the Appearance -> Menus panel in your site admin. Now, instead of seeing some text suggesting that your theme doesn’t natively support menus, you’ll see some Theme Location options.

You can now use the visual menu creator on this admin panel to create your menu(s). Give them each a name, and then assign a menu to a location with the pull-down options.