0

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!

2
  • 1
    Does this answer your question? Two different menus for two different locations? Commented Mar 13, 2020 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! Commented Mar 14, 2020 at 0:45

1 Answer 1

1

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/
and
https://developer.wordpress.org/reference/functions/register_nav_menu/
for reference

1
  • 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! Commented Mar 14, 2020 at 0:53

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.