参考函数wp_get_nav_menu_items()https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/#
它返回一个对象,其中包含给定菜单的所有菜单项,包括子菜单项,按照它们在仪表板上排列的顺序。它不会将子菜单项与其父项组合在一起,这会使创建自己的菜单变得有点困难。有没有办法安排对象,以便子项在其父项中的数组内分组?
function get_navbar_items() {
// wordpress does not group child menu items with parent menu items
$navbar_items = wp_get_nav_menu_items("Navbar");
$child_items = [];
// pull all child menu items into separate object
foreach ($navbar_items as $key => $item) if ($item->menu_item_parent) {
array_push($child_items, $item);
unset($navbar_items[$key]);
}
// push child items into their parent item in the original object
foreach ($navbar_items as $item)
foreach ($item as $key => $child)
if ($child->menu_item_parent == $item->post_name) {
if (!$item->child_items) $item->child_items = [];
array_push($item->child_items, $child);
unset($child_items[$key]);
}
// return navbar object where child items are grouped with parents
return $navbar_items;
}
要解决您的问题,您可以更改以下两行:
foreach ($item as $key => $child)
if ($child->menu_item_parent == $item->post_name) {
附:
foreach ($child_items as $key => $child)
if ($child->menu_item_parent == $item->object_id) {