Using WordPress ‘has_nav_menu()’ PHP function

The has_nav_menu() WordPress PHP function determines whether a registered nav menu location has a menu assigned to it.

Usage

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

Parameters

  • $location (string) – Required. Menu location identifier.

More information

See WordPress Developer Resources: has_nav_menu()

Examples

Displaying a Primary Menu

If a primary menu has been assigned to a location, this example will display it.

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

If a footer menu has been assigned to a location, this example will display it.

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

Displaying a Secondary Menu with a Custom Container

If a secondary menu has been assigned to a location, this example will display it with a custom container.

if (has_nav_menu('secondary')) {
    wp_nav_menu(array(
        'theme_location' => 'secondary',
        'container' => 'nav',
        'container_class' => 'secondary-menu'
    ));
}

Displaying a Social Menu with a Custom Menu Class

If a social menu has been assigned to a location, this example will display it with a custom menu class.

if (has_nav_menu('social')) {
    wp_nav_menu(array(
        'theme_location' => 'social',
        'menu_class' => 'social-menu'
    ));
}

Displaying a Mobile Menu with a Custom Walker

If a mobile menu has been assigned to a location, this example will display it with a custom walker.

if (has_nav_menu('mobile')) {
    wp_nav_menu(array(
        'theme_location' => 'mobile',
        'walker' => new Custom_Walker_Nav_Menu()
    ));
}