Theme development – Automatically menu creation

I’ve been working for a couple of days with automatic creation of menu upon theme activation in wordpress. I’ve achieved the creation of menu and it’s working as expected, except i want to add sub items to some of menu items.
For that moment i have

Home
Menu item 1
Menu item 2

What I’m trying to achieve is:

Home
Menu item 1 – Sub item 1, – Sub item 2
Menu item 2

I’ve been searching for the whole day without result. Could anybody help?

Here is my code so far:

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

}

Read more here:: Theme development – Automatically menu creation

Leave a Reply

Your email address will not be published. Required fields are marked *