我已经工作了几天,在wordpress中激活主题后自动创建菜单。我已经完成了菜单的创建,并且按预期工作,但我想将子项添加到某些菜单项中。 那一刻我有
我想要实现的是:
我整天都在搜索,但没有结果。有人可以帮忙吗?
到目前为止,这是我的代码:
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' => '/',
'Menu item 2' => '/',
'Menu item 3' => '/',
);
generate_nav_menu('Primary Menu', $primary_menu_items, 'primary');
}
}
function generate_nav_menu_item($term_id, $title, $url)
{
wp_update_nav_menu_item($term_id, 0, array(
'menu-item-title' => sprintf(__('%s', 'text_domain'), $title),
'menu-item-url' => home_url('/' . $url),
'menu-item-status' => 'publish'
));
}
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_location)
{
generate_nav_menu_item($menu_primary_obj->term_id, $page_name, $page_location);
}
$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);
}