WordPress+Nuxt3前后端分离项目,实现不限层级的多维数组菜单
使用 WordPress+Nuxt3做前后端分离项目时,菜单需要多维数组,且不限层级,可以使用递归函数很方便地将 wp_get_nav_menu_items
返回的对象数组转换为多维数组,实现不限层级的转换。
/**
* 输出菜单为多维数组
* 不限层级
*
* @param [type] $items
* @param integer $parent_id
* @return void
* @DateTime 2023-04-25
* @Author 萨龙龙 @ admin@salongweb.com
* @copyright 萨龙网络:https://salongweb.com
* @version 1.0
*/
function salong_convert_menu_items_to_array($items, $parent_id = 0)
{
$menu_items = array();
foreach ($items as $item) {
if ((int) $item->menu_item_parent === $parent_id) {
$menu_item = array(
'id' => $item->ID,
'title' => $item->title,
'url' => $item->url,
'children' => array(),
);
$children = salong_convert_menu_items_to_array($items, $item->ID);
if (!empty($children)) {
$menu_item['children'] = $children;
}
$menu_items[] = $menu_item;
}
}
return $menu_items;
}
$menu_locations = get_nav_menu_locations(); // 获取换所有菜单项
$header_menu_id = $menu_locations['header-menu']; // 头部菜单 ID
$menu_items = wp_get_nav_menu_items($header_menu_id);
$menu_items_array = salong_convert_menu_items_to_array($menu_items);
print_r($menu_items_array);