Using WordPress ‘has_nav_menu’ PHP filter

The has_nav_menu WordPress PHP filter checks if a navigation menu is assigned to a specified location.

Usage

add_filter('has_nav_menu', 'your_custom_function', 10, 2);
function your_custom_function($has_nav_menu, $location) {
    // your custom code here
    return $has_nav_menu;
}

Parameters

  • $has_nav_menu (bool): Indicates whether a menu is assigned to a location.
  • $location (string): The menu location to check.

More information

See WordPress Developer Resources: has_nav_menu

Examples

Show a custom message if no menu is assigned

This example shows a custom message if no menu is assigned to the specified location.

add_filter('has_nav_menu', 'show_custom_message_if_no_menu', 10, 2);
function show_custom_message_if_no_menu($has_nav_menu, $location) {
    if (!$has_nav_menu) {
        echo 'No menu assigned to this location.';
    }
    return $has_nav_menu;
}

Disable menu for a specific location

This example disables the menu for a specific location (e.g., ‘header_menu’).

add_filter('has_nav_menu', 'disable_menu_for_specific_location', 10, 2);
function disable_menu_for_specific_location($has_nav_menu, $location) {
    if ('header_menu' === $location) {
        return false;
    }
    return $has_nav_menu;
}

Set a default menu for a location

This example sets a default menu for a specific location (e.g., ‘footer_menu’) if no menu is assigned.

add_filter('has_nav_menu', 'set_default_menu_for_location', 10, 2);
function set_default_menu_for_location($has_nav_menu, $location) {
    if (!$has_nav_menu && 'footer_menu' === $location) {
        wp_nav_menu(array('theme_location' => 'default_footer_menu'));
        return true;
    }
    return $has_nav_menu;
}

Show a custom menu for logged-in users

This example shows a custom menu for logged-in users and the regular menu for logged-out users.

add_filter('has_nav_menu', 'show_custom_menu_for_logged_in_users', 10, 2);
function show_custom_menu_for_logged_in_users($has_nav_menu, $location) {
    if (is_user_logged_in()) {
        wp_nav_menu(array('theme_location' => 'logged_in_menu'));
        return true;
    }
    return $has_nav_menu;
}

Change menu location for mobile devices

This example changes the menu location for mobile devices, showing a mobile-specific menu instead.

add_filter('has_nav_menu', 'change_menu_location_for_mobile_devices', 10, 2);
function change_menu_location_for_mobile_devices($has_nav_menu, $location) {
    if (wp_is_mobile() && 'header_menu' === $location) {
        wp_nav_menu(array('theme_location' => 'mobile_header_menu'));
        return true;
    }
    return $has_nav_menu;
}