get_nav_menu_locations()
Uses: get_theme_mod()
Used By: has_nav_menu()
1 time — 0.000063 sec (very fast) | 50000 times — 1 sec (very fast)
No Hooks.
Return
Int[]
. Associative array of registered navigation menu IDs keyed by their location name. If none are registered, an empty array.
Usage
get_nav_menu_locations();
Examples
#1 Get the ID of the menu that is attached to the specified area [auto-translate]
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 Allows 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.8
function get_nav_menu_locations() { $locations = get_theme_mod( 'nav_menu_locations' ); return ( is_array( $locations ) ) ? $locations : array(); }