WordPress主题开发-自动创建菜单

时间:2019-03-14 15:31:15

标签: php wordpress

我已经工作了几天,在wordpress中激活主题后自动创建菜单。我已经完成了菜单的创建,并且按预期工作,但我想将子项添加到某些菜单项中。 那一刻我有

  • 首页
  • 菜单项1
  • 菜单项2

我想要实现的是:

  • 首页
  • 菜单项1-子项1,-子项2
  • 菜单项2

我整天都在搜索,但没有结果。有人可以帮忙吗?

到目前为止,这是我的代码:

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

}

0 个答案:

没有答案