查看的代码wp_update_nav_menu_item()
第三个参数是关于您尝试更新/创建的菜单项的数据数组。该数组中接受的项目之一是menu-item-parent-id
. 如果将父菜单项的ID值作为菜单项数据数组的一部分传递给该键,则问题应该得到解决。
编辑:我还没有对此进行测试,但从理论上讲,假设您之前所拥有的一切都是正确的,这将适用于您
add_action(\'after_switch_theme\', \'my_after_switch_theme\');
add_action(\'after_setup_theme\', \'my_after_setup_theme\');
function my_after_setup_theme()
{
register_nav_menus(array(
\'primary\' => __(\'Main Menu\', \'\'),
));
}
function my_after_switch_theme()
{
$menu_check = get_option(\'menu_check\');
if (!$menu_check) {
$primary_menu_items = array(
\'Home\' => array(\'url\' => \'/\'),
\'Menu item 2\' => array(
\'url\' => \'/\',
\'sub-items\' => array(
\'Sub item 1\' => array(\'url\' => \'/\'),
\'Sub item 2\' => array(\'url\' => \'/\')
)),
\'Menu item 3\' => array(\'url\' => \'/\'),
);
generate_nav_menu(\'Primary Menu\', $primary_menu_items, \'primary\');
}
}
function generate_nav_menu_item($term_id, $title, $data, $parent = false)
{
if (!$data[\'url\']) {
return;
}
$args = array(
\'menu-item-title\' => sprintf(__(\'%s\', \'text_domain\'), $title),
\'menu-item-url\' => home_url(\'/\' . $data[\'url\']),
\'menu-item-status\' => \'publish\'
);
if ($parent) {
$args[\'menu-item-parent-id\'] = $parent;
}
$item_id = wp_update_nav_menu_item($term_id, 0, $args );
if (!empty($data[\'sub-items\']) && !is_wp_error($item_id)) {
foreach ($data[\'sub-items\'] as $sub_item_title => $item) {
generate_nav_menu_item($term_id, $sub_item_title, $item, $item_id);
}
}
}
function generate_nav_menu($menu_name, $menu_items_array, $location_target)
{
$menu_primary = $menu_name;
wp_create_nav_menu($menu_primary);
$menu_primary_obj = get_term_by(\'name\', $menu_primary, \'nav_menu\');
foreach ($menu_items_array as $page_name => $page_data) {
generate_nav_menu_item($menu_primary_obj->term_id, $page_name, $page_data);
}
$locations_primary_arr = get_theme_mod(\'nav_menu_locations\');
$locations_primary_arr[$location_target] = $menu_primary_obj->term_id;
set_theme_mod(\'nav_menu_locations\', $locations_primary_arr);
//update_option(\'menu_check\', true);
}