2

I'm trying to create a theme which when activated, sets up a primary navigation, adds the homepage to it and then enables it in the correct location.

Here's what I've got so far:

register_nav_menu('Primary', 'Primary Navigation');

$primary_nav_menu_id = wp_create_nav_menu('Primary');

wp_update_nav_menu_item($primary_nav_menu_id, 0, array(
    'menu-item-title' =>  __('Home'),
    'menu-item-classes' => 'home',
    'menu-item-url' => home_url( '/' ), 
    'menu-item-status' => 'publish'
));

The above creates the menu, adds a link to the homepage but how would I go about automatically assigning this menu a theme location of 'Primary Navigation'?

Is this possible?

2 Answers 2

3

You need to first collect the menu locations, then set the primary menu location with the menu id.

// Set the menu to primary menu location
$locations = get_theme_mod( 'nav_menu_locations' );
$locations['primary'] = $primary_nav_menu_id;
set_theme_mod ( 'nav_menu_locations', $locations );

Here I assume 'primary' is theme location referring to 'Primary Navigation'.

1
0

The other answer is the short version for this. However, I made a function, that does a bit more. It does this:

  • It gets the locations (so the new menu can be added later)
  • It gets any menu by the name 'Mobile Menu' and get's the ID for that.
  • It sets the 'Mobile Menu' to be active for the display_location for the navigation called nav-mobile
  • And then it saves it all.
<?php
add_action( 'init', function() {
  // Variables
  $location_name = 'nav-mobile'; // As it's named in register_nav_menus( ... )
  $menu_name = 'Mobile Menu'; // The name of the menu in the WP backend
  $save_new_locations = false; // To only save, if it isn't set already
  $locations = get_theme_mod( 'nav_menu_locations' ); // Get all nav_locations

  if( ! isset( $locations[ $location_name ] ) ){
    $menus = get_terms( 'nav_menu' ); 
    $menus = array_combine( wp_list_pluck( $menus, 'term_id' ), wp_list_pluck( $menus, 'name' ) ); 
    // Above-written line matches id to menu name, like this:
    // [ 
    //   4129 => 'my-navigation',
    //   4123 => 'my-other-navigation',
    //   ...
    // ]
    // where 4129 and 4123 is the id of the menus 

    $mobile_menu_key = array_search( $menu_name, $menus ); // Finds ID
    if( !empty( $mobile_menu_key ) ){
      $locations[ $location_name ] = $mobile_menu_key;
      $save_new_locations = true;
    }
  }

  if( $save_new_locations ){
    set_theme_mod( 'nav_menu_locations', $locations );
  }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.