I'm trying to swap out the main menu of a page if it uses a specific page template.

This was working perfectly until I added a 2nd menu to the page.

I would greatly appreciate any guidance on how to target only the primary-menu and not all the menus on the page. I tried 'primary-menu' but did not work.

In functions.php:

add_filter('wp_nav_menu_args', function ($args) {
  if (is_page_template('page-template-custom.php')) {
    $args['menu'] = 'custom-menu';
  return $args;

Thanks very much!

  • 1
    Does this answer your question? Two different menus for two different locations?
    – Michael
    Mar 13 '20 at 22:55
  • Thanks is brilliant! Thank you Michael! I had to make a small modification though as the brackets may be misplaced and swapped "is_page" with "is_page_template" and voila!
    – Chumtarou
    Mar 14 '20 at 0:45

The $args the filter is receiving includes the theme_location used when the menu was registered, so assuming your main location is primary, you can add the following to your if statement to target only that menu:

    if ( 
      is_page_template( 'page-template-custom.php' ) && 
      isset( $args['theme_location'] ) &&
      'primary' === $args['theme_location'] )
    ) { ...

See: https://developer.wordpress.org/reference/hooks/wp_nav_menu_args/
for reference

  • This is perfect and works great! While this is similar to the link provided by Micheal, this solves my issue exactly for page templates - much gratitude thank you!
    – Chumtarou
    Mar 14 '20 at 0:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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