如何添加“活动"类到 wp_nav_menu() 当前菜单项(简单的方法) [英] How to add "active" class to wp_nav_menu() current menu item (simple way)

查看:27
本文介绍了如何添加“活动"类到 wp_nav_menu() 当前菜单项(简单的方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用入门主题 _Underscores 和 Bootstrap 创建自定义 Wordpress 主题.

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

我想修改 wp_nav_menu 以便它分配当前菜单项 .active 类而不是默认的 .current-menu-item>.我需要这个才能使用 Bootstrap 中的 .active 类.

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.

这是我所拥有的(额外的东西来自 WP,所以请向右滚动):

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>

这是我需要的:

<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>

我更愿意在不修改 ../wp-includes/nav-menu-template.php 并且不使用 JS 的情况下实现这一点.

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

更新:我在发布此问题之前找到了答案,但由于我很难找到它,因此将其发布为 QA 以希望节省一些时间.

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.

推荐答案

只需将此代码粘贴到functions.php文件中即可:

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;
}

有关 wordpress.org 的更多信息:

More on wordpress.org:

这篇关于如何添加“活动"类到 wp_nav_menu() 当前菜单项(简单的方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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