如何将 Wordpress 的“nav_menu_link_attributes"添加到特定菜单? [英] How can I add Wordpress's 'nav_menu_link_attributes' to a specific menu?

查看:18
本文介绍了如何将 Wordpress 的“nav_menu_link_attributes"添加到特定菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个设置了多个菜单的 Wordpress 网站.我想使用nav_menu_link_attributes"向其中一个菜单中的菜单项添加自定义属性,但这会将属性添加到所有菜单.我如何将其限制为一个特定的菜单?我找不到有关此问题的任何文档.

I'm working on a Wordpress website that has multiple menus set up. I wanted to add custom attributes to the menu items in one of the menus using 'nav_menu_link_attributes', but that adds the attributes to all of the menus. How would I limit this to just one specific menu? I can't find any documentation on this question.

我当前的代码是:

function add_menu_atts($atts){
  $atts['data-inventory-link'] = $atts['href'];
  $atts['data-model'] = $atts['title'];
  return $atts;
}
add_filter('nav_menu_link_attributes', 'add_menu_atts');

推荐答案

您使用的过滤器 nav_menu_link_attributes 也支持其他参数.您可以传入第二个参数 $item 和包含项目详细信息的第三个参数 $args.尝试这样的事情:

The filter you are using nav_menu_link_attributes supports other arguments as well. You can pass in a 2nd parameter $item and a 3rd parameter $args which contains the item details. Try something like this:

function add_menu_atts($atts, $item, $args){
  // your check for primary menu location
  if( $args->theme_location == 'primary' ) {
    $atts['data-inventory-link'] = $atts['href'];
    $atts['data-model'] = $atts['title'];
  }     

  return $atts;
}
add_filter('nav_menu_link_attributes', 'add_menu_atts', 10, 3);

这篇关于如何将 Wordpress 的“nav_menu_link_attributes"添加到特定菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆