您可以使用get_nav_menu_locations()
要获取正在使用的位置数组(已为其分配菜单),它显示如下:
Array
(
[header-menu] => 4
[extra-menu] => 6
)
the
4
和
6
是菜单ID,我想你已经有了ID,所以这应该足够了,现在的问题是,如果没有菜单位置被使用,或者根本没有位置,数组将显示为空,这并不意味着没有显示菜单,因为在主题中可能有
wp_nav_menu( array( \'theme_location\' => \'whatever\' ) )
正在使用,Wordpress将:
默认情况下,当找不到指定的菜单或位置时,WordPress会显示第一个非空菜单
在这种情况下,您可以使用get_terms( \'nav_menu\' )
, 它将显示如下数组:
Array
(
[0] => WP_Term Object
(
[term_id] => 6
[name] => Another Menu
[slug] => another-menu
[term_group] => 0
[term_taxonomy_id] => 6
[taxonomy] => nav_menu
[description] =>
[parent] => 0
[count] => 2
[filter] => raw
)
[1] => WP_Term Object
(
[term_id] => 4
[name] => Main Navigation Menu
[slug] => main-navigation-menu
[term_group] => 0
[term_taxonomy_id] => 4
[taxonomy] => nav_menu
[description] =>
[parent] => 0
[count] => 12
[filter] => raw
)
)
您可以检查哪个是
non-empty
菜单检查
[count]
值,或者您可以找到第一个空菜单项并添加菜单项,因为我知道这是您的目标。
以下是循环所有菜单的所有菜单项的代码:
$menus = get_terms(\'nav_menu\');
foreach ($menus as $menu) {//we loop all menus
$menu_id = $menu->term_id;//we get the ID
$menu_items_array = wp_get_nav_menu_items($menu_id);//we get the menu
foreach ($menu_items_array as $menu_item) {//we loop all the menu items of the menu
if($menu_item->post_name == "home") { //you can add more conditions here to check if its the home link
//THIS IS THE HOME MENU ITEM
echo "<pre>";
print_r($menu_item);//here a list of values that you can use
echo "</pre>";
}
}
}