Using WordPress ‘get_nav_menu_locations()’ PHP function

The get_nav_menu_locations() WordPress PHP function retrieves all registered navigation menu locations and the menus assigned to them.

Usage

$locations = get_nav_menu_locations();

Parameters

  • None

More information

See WordPress Developer Resources: get_nav_menu_locations()

Examples

Display all menu locations and their assigned menus

This code snippet displays all registered menu locations and the menus assigned to them.

$locations = get_nav_menu_locations();
foreach ($locations as $location => $menu_id) {
    echo "Location: " . $location . " | Menu ID: " . $menu_id . "<br>";
}

Display a specific menu by location

This code snippet displays the menu assigned to the ‘header-menu’ location.

$menu_location = 'header-menu';
if (isset($locations[$menu_location])) {
    wp_nav_menu(array('menu' => $locations[$menu_location]));
}

Check if a menu is assigned to a specific location

This code snippet checks if a menu is assigned to the ‘footer-menu’ location.

$menu_location = 'footer-menu';
if (isset($locations[$menu_location]) && $locations[$menu_location] != 0) {
    echo "A menu is assigned to the footer-menu location.";
} else {
    echo "No menu is assigned to the footer-menu location.";
}

Display a fallback message if no menu is assigned to a location

This code snippet displays a fallback message if no menu is assigned to the ‘sidebar-menu’ location.

$menu_location = 'sidebar-menu';
if (isset($locations[$menu_location]) && $locations[$menu_location] != 0) {
    wp_nav_menu(array('menu' => $locations[$menu_location]));
} else {
    echo "Please assign a menu to the sidebar-menu location.";
}

Get the menu name of a menu assigned to a location

This code snippet retrieves the menu name of the menu assigned to the ‘main-menu’ location.

$menu_location = 'main-menu';
if (isset($locations[$menu_location])) {
    $menu_object = wp_get_nav_menu_object($locations[$menu_location]);
    echo "Menu Name: " . $menu_object->name;
}