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
1.0k views
in Technique[技术] by (71.8m points)

wordpress - How to add "active" class to wp_nav_menu() current menu item (simple way)

I am creating custom Wordpress theme using a starter theme _Underscores and Bootstrap.

I would like to modify wp_nav_menu so that it assigns the current menu item .active class instead of the default .current-menu-item. I need this in order to use .active class from Bootstrap.

Here is what I have (extra stuff comes from WP so please scroll to the right):

<ul id="menu-main-menu" class="nav navbar-nav">
   <li id="menu-item-14" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-13 current_page_item menu-item-14"><a href="">item1</a></li>
   <li id="menu-item-12" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-12"><a href="">item2</a></li>
</ul>

And here is what I need:

<ul id="menu-main-menu" class="nav navbar-nav">
   <li id="menu-item-14" class="active menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-13 current_page_item menu-item-14"><a href="">item1</a></li>
   <li id="menu-item-12" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-12"><a href="">item2</a></li>
</ul>

I would prefer to achieve this without modifying ../wp-includes/nav-menu-template.php and without using JS.


UPDATE: I found the answer just before posting this question, but since I had a rather hard time finding it, posting this as a QA to hopefully save someone some time.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Just paste this code into functions.php file:

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
  if (in_array('current-menu-item', $classes) ){
    $classes[] = 'active ';
  }
  return $classes;
}

More on wordpress.org:


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

...