Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

php - How to add class to link in wp_nav_menu?

I am trying to out a wp menu without ul and li and have a class added to the element.

I have tried adding this in my function.php

function add_menuclass($ulclass) {
  return preg_replace('/<a /', '<a class="list-group-item"', $ulclass, 1);
}
add_filter('wp_nav_menu','add_menuclass');

And in my template I have:

<?php
 $menuParameters = array(
   'menu'  => 'Videos',
   'container'       => false,
   'echo'            => false,
   'items_wrap'      => '%3$s',
   'depth'           => 0,
);

  echo strip_tags(wp_nav_menu( $menuParameters ), '<a>' );
?>

But the output only applies the class to the first item and not all of the <a>s as expected.

<div class="list-group">
   <a class="list-group-item" href="#">First item</a>
   <a href="#">Second item</a>
</div>

I am trying to achieve this, basically to apply that class to ALL my item (not sure why it applies it to only one) - No jQuery please.

<div class="list-group">
   <a class="list-group-item" href="#">First item</a>
   <a class="list-group-item" href="#">Second item</a>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Taking a hint from this answer which I found was the most concise about adding classes to the list items of the menus, I used nav_menu_link_attributes filter which does work well for adding classes.

In your functions.php, add:

function add_menu_link_class( $atts, $item, $args ) {
  if (property_exists($args, 'link_class')) {
    $atts['class'] = $args->link_class;
  }
  return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_menu_link_class', 1, 3 );

Optionally, you may want to add the option to add classes to list items:

function add_menu_list_item_class($classes, $item, $args) {
  if (property_exists($args, 'list_item_class')) {
      $classes[] = $args->list_item_class;
  }
  return $classes;
}
add_filter('nav_menu_css_class', 'add_menu_list_item_class', 1, 3);

Now, in your template, to build a menu you just add two new arguments, e.g.:

wp_nav_menu([
    'theme_location'=> 'primary_navigation',
    'menu_class'    => 'navbar-nav ml-auto flex-nowrap',
    'list_item_class'  => 'nav-item',
    'link_class'   => 'nav-link m-2 menu-item nav-active'
]);

Works well with themes with multiple menus which have different appearance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...