Update Theme Location Programatically

I’ve been trying to update my theme location programmtically and while the menu gets created with menu items, the theme location never gets set.

Here is what I have:

Read More
function create_my_menu() {
if(!is_nav_menu('primary-menu')) {
  $menu_id = wp_create_nav_menu('primary-menu');
  //$menu = array( 'menu-item-type' => 'custom', 'menu-item-url' => get_home_url('/'),'menu-item-title' => 'Home', 'menu-item-status' => 'publish' );
  $menu = get_term_by('name', 'primary-menu', 'nav_menu');
  wp_update_nav_menu_item($menu->term_id, 0, array( 'menu-item-type' => 'custom', 'menu-item-url' => get_home_url('/'),'menu-item-title' => 'Home', 'menu-item-status' => 'publish' ));
//    wp_update_nav_menu_item( $menu_id, 0, $menu );
  $locations = get_theme_mod('nav_menu_locations');
  $locations['primary-menu'] = $menu->term_id.  
  set_theme_mod('nav_menu_locations', $locations);
}
}

My menu is registered in my functions file.

add_action( 'init', 'register_my_menu' );

function register_my_menu() {
register_nav_menu( 'primary-menu', __( 'Primary Menu' ) );
}

EDIT

I’m working on a plugin for a multisite setup. I need the menu to be created when a user creates a new site.

I suppose I could modify the default menu that gets created when wordpress is installed.

Related posts

Leave a Reply

2 comments

  1. Generally speaking, you shouldn’t be (or need to be) “updating” the theme_location for a custom nav menu. The theme_location is the template location for a given nav menu.

    If you need to do dynamic manipulation of a custom nav menu, you might be better off targeting the id of the menu, rather than the theme_location. Your code above seems to be conflating the two. (Note that wp_create_nav_menu() accepts a menu name as an argument, rather than a menu theme location.)

    But, what are you actually trying to do by dynamically manipulating menus in this way? Perhaps we can find a better solution.

    EDIT

    Based on your clarification: you definitely need to target the Menu Name, rather than the Theme Location.

    One Theme Location correlates to one defined (physical) location within the Theme template. A Theme Location is not a menu itself, but rather a marker to indicate where a menu is output.

    If you need to generate a default menu (and I’m really not sure why you need to do this; simply define a proper callback to wp_nav_menu() instead), then you need to pass the Menu Name to wp_create_nav_menu().