Registering a menu location
A location is a named slot in the theme that the user can later assign a menu to in
Appearance → Menus. Locations are declared in functions.php:
<?php register_nav_menu( $location, $description ); ?>
Several locations at once:
register_nav_menus( [
$location1 => $description1,
$location2 => $description2,
] );
Registration must happen on the after_setup_theme hook:
add_action( 'after_setup_theme', 'register_menus' );
function register_menus() {
register_nav_menu( 'primary', 'Primary menu' );
}
Printing a menu in a template
<?php wp_nav_menu( $args ); ?>
<?php wp_nav_menu( [
'theme_location' => 'top',
'container' => false,
'items_wrap' => '<ul>%3$s</ul>',
] ); ?>
Useful snippets
Adding a CSS class to the ul element:
wp_nav_menu( [
'theme_location' => 'top-menu',
'menu_class' => '[add-your-class-here]',
] );
Stripping the ul and li wrappers completely and keeping only the links — handy when the layout uses
its own markup:
echo strip_tags( wp_nav_menu( [
'container' => false,
'echo' => false,
'items_wrap' => '%3$s',
'depth' => 0,
] ), '<a>' );
Building a link to a page by its slug, without hardcoding the URL:
<a href="<?= get_permalink( get_page_by_path( 'clients' ) ) ?>">...</a>
Andrew Dorokhov