has_nav_menu()
Checks if a registered menu location has a menu assigned to it. Conditional tag.
Uses: get_nav_menu_locations()
Hooks from the function
Returns
true|false.
Usage
if( has_nav_menu( $location ) ){
// ...
}
- $location(string) (required)
- Identifier of the menu location specified when registering the menu area in the register_nav_menu() function.
Examples
#1 Usage Demo
if ( has_nav_menu( 'primary' ) ) {
wp_nav_menu( [ 'theme_location' => 'primary' ] );
} #2 Display the menu, if there is one
Let's say there are several menu areas registered in the theme.
functions.php
add_action( 'after_setup_theme', function () {
// Miscellaneous theme settings
// ...
// Register areas for menus
register_nav_menus( array(
'header-menu' => 'Header menu area',
'footer-menu' => 'Footer menu area',
) );
} );
Now let's check if the menu is attached to the specified area and if it is, display the menu:
header.php
if( has_nav_menu( 'header-menu' ) ){
wp_nav_menu( [ 'theme_location' => 'header-menu' ] );
}
footer.php
if( has_nav_menu('footer-menu') ){
wp_nav_menu( array( 'theme_location' => 'footer-menu' ) );
}
Changelog
| Since 3.0.0 | Introduced. |
has_nav_menu() has nav menu code WP 6.9.1
function has_nav_menu( $location ) {
$has_nav_menu = false;
$registered_nav_menus = get_registered_nav_menus();
if ( isset( $registered_nav_menus[ $location ] ) ) {
$locations = get_nav_menu_locations();
$has_nav_menu = ! empty( $locations[ $location ] );
}
/**
* Filters whether a nav menu is assigned to the specified location.
*
* @since 4.3.0
*
* @param bool $has_nav_menu Whether there is a menu assigned to a location.
* @param string $location Menu location.
*/
return apply_filters( 'has_nav_menu', $has_nav_menu, $location );
}