How can I create an auto-populated menu that is automatically assigned to a location?

So basically you are asking how to create a custom menu by code and assign it to a menu location:

 //give your menu a name
$name="theme default menu";
 //create the menu
$menu_id = wp_create_nav_menu($name);
 //then get the menu object by its name
$menu = get_term_by( 'name', $name, 'nav_menu' );
 //then add the actuall link/ menu item and you do this for each item you want to add
wp_update_nav_menu_item($menu->term_id, 0, array(
    'menu-item-title' =>  __('Home'),
    'menu-item-classes' => 'home',
    'menu-item-url' => home_url( "https://wordpress.stackexchange.com/" ), 
    'menu-item-status' => 'publish'));
// you add as many items ass you need with wp_update_nav_menu_item()

//then you set the wanted theme  location
$locations = get_theme_mod('nav_menu_locations');
$locations['LOCATION_NAME'] = $menu->term_id;
set_theme_mod( 'nav_menu_locations', $locations );

So all you have to do is add as many links as you want, change LOCATION_NAME to the actual location name and make sure this code is only run once.

Leave a Comment