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

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

问题描述

我正在使用入门主题_Underscores创建自定义Wordpress主题.我还将Bootstrap用作前端框架.

I am creating custom Wordpress theme using a starter theme _Underscores. I am also using Bootstrap as a front-end framework.

我想修改wp_nav_menu,以便它分配当前菜单项class ="active"而不是class ="current-menu-item"(默认).或者至少分配两个类.我需要这个,以便使用bootstrap.css中的.active类.

I would like to modify wp_nav_menu so that it assigns current menu item class="active" instead of class="current-menu-item" (which is default). Or maybe at least assigns both of these classes. I need this in order to use .active class from bootstrap.css.

这是我所拥有的示例(所有这些类都是wp生成的,请滚动以查看我的意思):

Here is the example of what I have (all these classes are wp generated, please scroll to see what I mean):

<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 do this in a correct way - don't want to change anything in ..wp-includes/nav-menu-template.php for sure, don't want to use js either.

好吧,我在发布这个问题之前就找到了答案(已经准备好了,这就是为什么它仍然以某种形式形成,就像我仍在寻找答案一样),但是我很难找到它,所以我决定将其发布为质量检查.我希望有人会觉得有用.

Well I found the answer just before posting this question (it was all ready, that's why it is still formed in a way as if I am still seeking the answer), but I had rather hard time finding it so I decided to post it as a QA. I hope someone will find this useful.

推荐答案

只需将此代码粘贴到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天全站免登陆