get_nav_menu_locations()
Gets an array of registered menu areas (menu locations) and the menu IDs attached to each area.
Menu areas are registered using the function register_nav_menu(). Then, a menu is created in the admin panel and attached to the existing area.
Uses: get_theme_mod()
Used By: has_nav_menu()
1 time — 0.000063 sec (very fast) | 50000 times — 1 sec (very fast)
No Hooks.
Returns
Int[]. An array of the form: 'menu_area_label' => menu id:
Array ( [location] => 694 [location2] => 796 )
Usage
$locations = get_nav_menu_locations();
Examples
#1 Get the ID of the menu that is attached to the specified area
We registered the menu location with register_nav_menu(). The location has the label my_location. Then we created a menu in the admin and attached it to that location. Then the following code will work like this:
$locs = get_nav_menu_locations(); print_r( $locs ); /* Will withdraw: Array ( [toolbar] => 694 ) */
#2 Let's allow the 'editor' role to modify menus
add_action( 'admin_menu', 'allow_menu_editor', 99 );
function allow_menu_editor() {
$arr_menu = array_filter( get_nav_menu_locations() );
if( ! empty( $arr_menu ) ){
$obj_role = get_role( 'editor' );
$obj_role->add_cap( 'edit_theme_options' );
}
} #3 Get nav menu title by it's id (slug)
$menu_name = 'menu1';
echo sprintf( '<h3>%s</h3>', get_nav_menu_title( $menu_name ) ?: __( 'Insert menus', 'textdomain' ) );
wp_nav_menu( [
'theme_location' => $menu_name,
'container' => '',
] );
$menu_name = 'menu2';
echo sprintf( '<h3>%s</h3>', get_nav_menu_title( $menu_name ) ?: __( 'Insert menus', 'textdomain' ) );
wp_nav_menu( [
'theme_location' => $menu_name,
'container' => '',
] );
function get_nav_menu_title( $menu_name ) {
$loc = get_nav_menu_locations( $menu_name )[ $menu_name ] ?? null;
if( ! $loc ){
return '';
}
return wp_get_nav_menu_object( $loc )->name;
}
Changelog
| Since 3.0.0 | Introduced. |
get_nav_menu_locations() get nav menu locations code WP 6.9.1
function get_nav_menu_locations() {
$locations = get_theme_mod( 'nav_menu_locations' );
return ( is_array( $locations ) ) ? $locations : array();
}