简体   繁体   English

如何将 wordpress 中的活动 class 添加到锚标签

[英]How to add active class in wordpress to anchor tag

<li>
  <a href="<?php echo site_url('/blog') ?>"
  <?php if(get_post_type()=='post') echo 'class="active"'?>>Blog</a>
</li>

I am trying to add active class to different links in navigation but this code gives an error.我正在尝试将活动 class 添加到导航中的不同链接,但此代码给出错误。 Can somebody correct the mistake in above-mentioned code?有人可以纠正上述代码中的错误吗?

How about another way?换一种方式怎么样?

function add_class_to_href( $classes, $item ) {
    if ( in_array('current_page_item', $item->classes) ) {
        $classes['class'] = 'active';
    }
    return $classes;
}
add_filter( 'nav_menu_link_attributes', 'add_class_to_href', 10, 2 );

Perhaps this is the way to go, if I understand correctly.如果我理解正确的话,也许这就是通往 go 的方法。 Anyways, hope this helps!无论如何,希望这会有所帮助!

I know it's a whole function, but this should work.我知道这是一个完整的 function,但这应该可以。 Paste this into function.php file.将此粘贴到function.php文件中。

Include the following jquery code to your footer and your page will work fine在您的页脚中包含以下 jquery 代码,您的页面将正常工作

$(".current_page_item a").addClass("active"); $(".current_page_item a").addClass("active");

Hope this will help you希望对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM