个性化阅读
专注于IT技术分析

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

引用函数wp_get_nav_menu_items()https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/#

它返回一个对象, 该对象具有给定菜单的所有菜单项, 包括子菜单项, 其排列顺序在仪表板上。它不会将子菜单项与其父项归为一组, 这会使创建自己的菜单有些困难。有没有一种方法可以安排对象, 以便子项在其父项的数组内分组?


#1


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

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) {

#2


        // wordpress does not group child menu items with parent menu items
        $menuLocations = get_nav_menu_locations();
        $navbar_items = wp_get_nav_menu_items($menuLocations['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 ($child_items 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;
赞(0)
未经允许不得转载:srcmini » 如何获得wp_get_nav_menu_items与父母分组子项目?

评论 抢沙发

评论前必须登录!