Paulund
2014-01-20 #wordpress

Display Menus When Location Is Assigned

In WordPress the user can create their own menus in the CMS area by just going to Appearance -> Menus. From this page you can then assign these menus to locations in the theme by choosing the theme location for the menu. These theme locations are setup by the theme developer and is done by using the function register_nav_menus(); The register nav menu function can be placed in the functions.php file.


register_nav_menus( array(
	'header_menu' => 'Header Menu',
	'footer_menu' => 'Footer Menu'
) );

When you navigate to the theme menu location page you will see two new theme locations for the header menu and the footer menu.

By default these menu locations won't have a menu assigned to them, when the user creates new menus they will need to assign them to the menu locations. To display these menus in the correct theme location you will need to place the function wp_nav_menu() in your theme in the position you want the menu to be displayed.


<?php

$defaults = array(
	'theme_location'  => '',
	'menu'            => '',
	'container'       => 'div',
	'container_class' => '',
	'container_id'    => '',
	'menu_class'      => 'menu',
	'menu_id'         => '',
	'echo'            => true,
	'fallback_cb'     => 'wp_page_menu',
	'before'          => '',
	'after'           => '',
	'link_before'     => '',
	'link_after'      => '',
	'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
	'depth'           => 0,
	'walker'          => ''
);

wp_nav_menu( $defaults );

?>

As you can see the first argument you can pass through the theme_location ID, this is how WordPress will know what menu to display in this location. If a menu isn't assigned to this theme location then WordPress will display links to all the pages created in your WordPress site. If you are creating a theme for a client this can be quite confusing to the user when they first see the menu with pages on there. To make sure that the menu is not displayed until the menu location has a menu assigned, you can use the WordPress function of has_nav_menu( $location ). This takes one parameter of the theme menu location ID, if a menu has been assigned then you can display the navigation menu.


if ( has_nav_menu( 'header_menu' ) ) {
     wp_nav_menu( array('theme_location' => 'header_menu') );
}

Changing Fallback Function

Another option to remove the page menu if the menu doesn't exist is to change the fallback property. By default the fallback function is set to wp_page_menu, changing this to false will make sure that no menu is returned.


wp_nav_menu( array('theme_location' => 'header_menu', 'fallback_cb' => false) );