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!
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!
Share Improve this question asked Mar 13, 2020 at 21:52 ChumtarouChumtarou 1031 bronze badge 2- 1 Does this answer your question? Two different menus for two different locations? – Michael 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! – Chumtarou Commented Mar 14, 2020 at 0:45
1 Answer
Reset to default 1The $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/reference/hooks/wp_nav_menu_args/
and
https://developer.wordpress/reference/functions/register_nav_menu/
for reference