最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Change menu based on page template via functions.php

programmeradmin2浏览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!

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
Add a comment  | 

1 Answer 1

Reset to default 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/reference/hooks/wp_nav_menu_args/
and
https://developer.wordpress/reference/functions/register_nav_menu/
for reference

发布评论

评论列表(0)

  1. 暂无评论