unregister_nav_menu()
云策文档标注
概述
unregister_nav_menu() 函数用于取消注册主题中的导航菜单位置。它通过移除全局变量中的位置标识符来实现,成功时返回 true,失败时返回 false。
关键要点
- 参数 $location 是必需的字符串,表示要取消注册的菜单位置标识符。
- 返回值是布尔值:成功返回 true,失败返回 false。
- 函数内部操作全局变量 $_wp_registered_nav_menus,如果移除后该变量为空,还会调用 _remove_theme_support('menus')。
- 注意:unregister_nav_menu() 仅从注册列表中移除位置,不处理主题修改中的 nav_menu_locations 数组,可能需要额外步骤完全删除位置。
代码示例
unregister_nav_menu( 'primary' );注意事项
用户贡献的笔记指出,要完全移除菜单位置,还需从 get_theme_mod('nav_menu_locations') 数组中删除位置标识符,并重置主题修改。这可以通过自定义函数如 delete_nav_menu_location() 实现。
原文内容
Unregisters a navigation menu location for a theme.
Parameters
$locationstringrequired-
The menu location identifier.
Source
function unregister_nav_menu( $location ) {
global $_wp_registered_nav_menus;
if ( is_array( $_wp_registered_nav_menus ) && isset( $_wp_registered_nav_menus[ $location ] ) ) {
unset( $_wp_registered_nav_menus[ $location ] );
if ( empty( $_wp_registered_nav_menus ) ) {
_remove_theme_support( 'menus' );
}
return true;
}
return false;
}
Changelog
| Version | Description |
|---|---|
| 3.1.0 | Introduced. |
Skip to note 3 content
studiolxv
Delete a previously registered location
Calling get_nav_menu_locations() will show you an array of all the nav location slugs and their associated menu ID you have registered/ and or used in the past. The get_nav_menu_locations() function checks a theme mod so to fully unregister/remove menu location we need an extra step missing from unregister_nav_menu() by removing the location slug from the get_theme_mod(‘nav_menu_locations’) array and then resetting the theme mod without the $location we want to remove.
/** * Delete a previously registered location * * @param $location The slug used to register the menu in the first place */ if (!function_exists('delete_nav_menu_location')) { function delete_nav_menu_location($location) { $locations = get_theme_mod('nav_menu_locations'); if (is_array($locations) && array_key_exists($location, $locations)) { unset($locations[$location]); set_theme_mod('nav_menu_locations', $locations); return true; } return false; } }Skip to note 4 content
Codex
Basic Example