如何让wp_get_nav_menu_items与父母分组子项目?

时间:2018-01-12 03:16:00

标签: php wordpress wordpress-theming

参考函数wp_get_nav_menu_items()https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/#

它返回一个对象,其中包含给定菜单的所有菜单项,包括子菜单项,按照它们在仪表板上排列的顺序。它不会将子菜单项与其父项组合在一起,这会使创建自己的菜单变得有点困难。有没有办法安排对象,以便子项在其父项中的数组内分组?

2 个答案:

答案 0 :(得分:0)

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;
}

答案 1 :(得分:0)

要解决您的问题,可以更改以下两行:

public void ConfigureServices(IServiceCollection services)
{
    // ...
        services.AddSingleton(new JoinableTaskFactory());
    // ...
}

使用:

foreach ($item as $key => $child)
        if ($child->menu_item_parent == $item->post_name) {