Register and display navigation menus in a WordPress theme
Menus are one of the first things a theme sets up. The theme declares menu locations, the site owner builds menus in Appearance → Menus and assigns them to the locations, and the templates print whatever menu is assigned. The theme never hard-codes the links.
Problem: A theme needs a header menu and a footer menu that the site owner can edit in the admin.
Solution: Declare the locations with register_nav_menus() on after_setup_theme, and print them in the templates with wp_nav_menu() and the theme_location argument.
Registering locations
In functions.php:
<?php
add_action( 'after_setup_theme', 'ha_register_menus' );
function ha_register_menus() {
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'textdomain' ),
'footer' => __( 'Footer Menu', 'textdomain' ),
) );
}
The keys (primary, footer) are used in the templates, the labels are shown in the admin.
Printing a menu
In header.php:
<?php
wp_nav_menu( array(
'theme_location' => 'primary',
'container' => 'nav',
'container_class' => 'site-nav',
'menu_class' => 'nav-menu',
'depth' => 2, // the menu and one level of sub-menus; 0 = all levels
'fallback_cb' => false, // print nothing if no menu is assigned
) );
Without 'fallback_cb' => false, a location without a menu shows a list of all pages, which is rarely what you want on a live site.
To print something around the menu only when it exists, check the location first:
<?php if ( has_nav_menu( 'footer' ) ) : ?>
<div class="footer-menu">
<?php wp_nav_menu( array( 'theme_location' => 'footer', 'depth' => 1 ) ); ?>
</div>
<?php endif; ?>
A class on the current item
WordPress already adds current-menu-item and current-menu-ancestor classes. If your CSS framework expects another class, add it with the nav_menu_css_class filter:
<?php
add_filter( 'nav_menu_css_class', 'ha_menu_active_class', 10, 3 );
function ha_menu_active_class( $classes, $item, $args ) {
if ( 'primary' === $args->theme_location && in_array( 'current-menu-item', $classes, true ) ) {
$classes[] = 'is-active';
}
return $classes;
}
NOTE: When you need different markup for the header and the footer, for example dropdowns in the header and a flat list in the footer, pass a custom walker class in the walker argument of wp_nav_menu() for the location that needs it.