get_nav_menu_locations()
云策文档标注
概述
get_nav_menu_locations() 函数用于检索所有已注册的导航菜单位置及其分配的菜单。它返回一个关联数组,键为位置名称,值为菜单ID,若无注册则返回空数组。
关键要点
- 函数返回类型为 int[],即关联数组,键是菜单位置名称,值是菜单ID。
- 如果未分配菜单,对应位置的值可能为0,表示无菜单。
- 内部实现基于 get_theme_mod('nav_menu_locations') 获取主题修改值。
- 自 WordPress 3.0.0 版本引入,是导航菜单系统的核心函数。
代码示例
// 示例1:获取所有菜单位置和菜单ID
$locations = get_nav_menu_locations();
print_r($locations); // 输出如 Array([main-menu] => 757, [footer-menu] => 0)
// 示例2:用户贡献笔记中的代码片段,允许编辑角色修改菜单
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');
}
}
add_action('admin_menu', 'allow_menu_editor', 999);注意事项
- 返回的数组可能包含值为0的项,表示该位置未分配菜单,需在代码中处理这种情况。
- 函数依赖于主题修改设置,更改主题或重置设置可能影响返回值。
- 与 has_nav_menu() 等函数配合使用,可检查特定位置是否有菜单。
原文内容
Retrieves all registered navigation menu locations and the menus assigned to them.
Source
function get_nav_menu_locations() {
$locations = get_theme_mod( 'nav_menu_locations' );
return ( is_array( $locations ) ) ? $locations : array();
}
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |
Skip to note 4 content
madastro
Allows the editor role to modify menus
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'); } } add_action( 'admin_menu', 'allow_menu_editor', 999);Skip to note 5 content
khangaitan
$menu_name = 'menu1'; $menu_item = wp_get_nav_menu_object( get_nav_menu_locations( $menu_name )[ $menu_name ] )->name; echo $menu_item ? $menu_item : __( 'Insert menus', 'textdomain' ); wp_nav_menu( array( 'theme_location' => $menu_name, 'container' => '' ) ); $menu_name = ''; $menu_name = 'menu2'; $menu_item = wp_get_nav_menu_object( get_nav_menu_locations( $menu_name )[ $menu_name ] )->name; echo $menu_item ? $menu_item : __( 'Insert menus', 'textdomain' ); wp_nav_menu( array( 'theme_location' => $menu_name, 'container' => '' ) ); $menu_name = ''; $menu_name = 'menu3'; $menu_item = wp_get_nav_menu_object( get_nav_menu_locations( $menu_name )[ $menu_name ] )->name; echo $menu_item ? $menu_item : __( 'Insert menus', 'textdomain' ); wp_nav_menu( array( 'theme_location' => $menu_name, 'container' => '' ) );Skip to note 6 content
Deepesh Dhakal
Just to Update on the ‘return’ statement, it returns ‘integer’ for individual ‘menu-location’ if no menu is assigned. To be precise, it returns an Array like so:
Returns an array like so
<br />
Array<br />
(<br />
[main-menu] => 757<br />
[mobile-menu] => 1506<br />
[footer-menu] => 0<br />
)<br />
main-menu and mobile-menu are assigned so they return Menu ID whereas footer-menu is unassigned and thus returns ‘0’.