has_nav_menu()WP 3.0.0

Determines whether a registered nav menu location has a menu assigned to it.

Hooks from the function

Return

true|false. Whether location has a menu.

Usage

has_nav_menu( $location );
$location(string) (required)
Menu location identifier.

Examples

3

#1 Usage Demo

if ( has_nav_menu( 'primary' ) ) {
	wp_nav_menu( [ 'theme_location' => 'primary' ] );
}
0

#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() code WP 6.4.3

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 );
}