将自定义数据属性添加到Wordpress导航菜单

Nic*_*ick 5 wordpress

我在stackoverflow上看过一些类似的问题,但我的有点不同......

我需要能够将自定义数据属性添加到wordpress菜单.我遇到的问题是我发现的所有解决方案,例如:

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 = 365;

  // inspect $item
  if ($item->ID == $menu_target) {
    $atts['data-reveal-id'] = 'myModal';
  }
  return $atts;
}
Run Code Online (Sandbox Code Playgroud)

允许您将相同的属性添加到所有菜单项.我需要的是,实际上是一种添加相同数据属性的方法,但在列表上的每个元素上使用不同的值.

这几乎是我需要达成的目标:

<ul id="myMenu">
    <li data-menuanchor="firstPage" class="active"><a href="#firstPage">First section</a></li>
    <li data-menuanchor="secondPage"><a href="#secondPage">Second section</a></li>
    <li data-menuanchor="thirdPage"><a href="#thirdPage">Third section</a></li>
    <li data-menuanchor="fourthPage"><a href="#fourthPage">Fourth section</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

因为我需要在这里使用这个插件:https://github.com/alvarotrigo/fullPage.js#fullpagejs

任何建议?

谢谢

Nic*_*ick 1

最后我用javascript解决了这个问题。

这就是我所做的:

(function() {
  var arrayList, key, val;

  arrayList = ['first', 'second', 'third', 'fourth'];

  for (key in arrayList) {if (window.CP.shouldStopExecution(1)){break;}
    val = arrayList[key];
    console.log("key is " + key + " and val is " + val);
    $('li').each(function(index) {
      if (parseInt(index) === parseInt(key)) {
        return $(this).attr('data-anchor', val);
      }
    });
  }
window.CP.exitedLoop(1);


}).call(this);
Run Code Online (Sandbox Code Playgroud)
  • 使用您需要的数据创建一个数组
  • Foreach 循环遍历数组
  • 在该循环内,循环遍历菜单项
  • 如果菜单索引与数组索引相同,则将数组值作为属性附加。

这也是一个 codepen 示例:http ://codepen.io/NickHG/pen/GmKqqE