Creating a WordPress Theme from Scratch: Adding Menus

Creating a WordPress Theme from Scratch: Adding Menus

As discussed in previous post, functions.php is automatically included in the processing of a theme. This is therefore the best place to add default settings that you want to a theme, as well as helper functions.

To make sure that a function is called on the initialisation of a theme you should use the following in the functions.php file:

function add_menus(){
// Do Stuff Here
}
add_action( ‘init’, ‘add_menus’ );

In order to register the menus for your theme you need to use: register_nav_menus with an array of ‘slugs’=>’descriptions’:

register_nav_menus(
array(
‘main_nav’ => ‘The Main Menu’,
‘footer_nav’ => ‘The Footer Menu’,
)
);

This will do two things.

1) It will add an ability to edit menus on the theme once activated:

Adding Theme Settings

 

It will also add all the menus that you have specified to the list of possible menus that you can use:
Menus of a Theme

 

Now to actually display the appropriate menu you just need to call wp_nav_menu(‘slug’).

So our example would be wp_nav_menu(‘main_nav’); or wp_nav_menu(‘footer_nav’);

This will print out whatever menu you have in those drop downs above.

However if one isn’t selected it seems to still show the menu with Home and About. So I created a wrapper in my functions.php as so:

function get_menu($menu){
$locations = get_nav_menu_locations();
if ($locations[$menu]){
wp_nav_menu(array(‘theme_location’=>$menu));
}
}

Now I simply call get_menu(‘main_nav’); and it will either show nothing if the menu is blank or it will be the actual menu selected.

That is it for menus for now. Remember to check how WordPress outputs the menus and change the CSS to suit how you want it to. (e.g. by default it uses menu-top-menu as the class). Or you can use a custom class  when calling wp_nav_menu():

wp_nav_menu( array( 'theme_location' => 'extra-menu', 'container_class' => 'my_extra_menu_class' ) );
Comments are closed.