如何将数据属性添加到< li>WordPress导航菜单中的元素 [英] how to add data attribute to a <li> element in wordpress nav menu

查看:58
本文介绍了如何将数据属性添加到< li>WordPress导航菜单中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在wordpress网站上使用fullpage.js,想使用它的功能之一,就是在li上添加一个类.但是要做到这一点,您需要添加数据属性data-menuanchor.

I'm using fullpage.js on a wordpress site and would like to use one of it's function wicht is to add a class on a li. But to do this you need to add the data attribute data-menuanchor .

我已经看到了:

add_filter( 'nav_menu_link_attributes', 'my_nav_menu_attribs', 10, 3 );
function my_nav_menu_attribs( $atts, $item, $args )
{
  // The ID of the target menu item
  $menu_target = 113;

  // inspect $item
  if ($item->ID == $menu_target) {
    $atts['data-menuanchor'] = 's1';

  }
  return $atts;
}

除了将属性添加到标签中并需要将其添加到li标签上之外,它均起作用.

It works excepts that it adds the attribute to the a tag and need it to be on the li tag.

此外,如果要对菜单上的所有项目执行此操作.我是否需要对所有物品都执行此功能?而且我想每次都必须重命名该函数吗?

Also, if I want to do it to all the items on the menu. Do I need to do this function for all the items? And I suppose I have to rename the function each time?

谢谢

推荐答案

我不确定WP是否为此具有特定的过滤器/方法.您将必须与 wp_nav_menu_items 一起进行一些手动DOM操作.

I'm not sure WP has a specific filter/method for this. You're gonna have to do some manual DOM manipulation along with wp_nav_menu_items.

https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/

function addDataAttr( $items, $args ) {
    $dom = new DOMDocument();
    $dom->loadHTML($items);
    $find = $dom->getElementsByTagName('li');

    foreach ($find as $item ) :
        $item->setAttribute('data-menuanchor','s1');
    endforeach;

    return $dom->saveHTML();

}

add_filter('wp_nav_menu_items', 'addDataAttr', 10, 2);

这篇关于如何将数据属性添加到< li>WordPress导航菜单中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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