[英]Add `active` class to li of current single page wordpress
Looking for your help and advices. 寻找您的帮助和建议。 I have a list of links to single
in Wordpress. 我在Wordpress中有一个指向single
链接的列表。 I need to place class active
only to li of active page. 我需要把类active
只有活动页面的李。
Should be like on this image 应该像这张图片
But it is: 但它是:
My wp-code: 我的wp代码:
<ul class="inline-list medium-6 large-4 skill-items">
<?php
$id = get_the_ID();
// echo $id;
$class;
$skills = new WP_Query( array(
'post_type' => 'skills',
'order' => 'ASC'
));
if ($skills->have_posts()) : while ($skills->have_posts()) : $skills->the_post();
// echo $post->ID;
if( $id == $post->ID) {$class = 'active';} else {$class = '';}
?>
<li class="<?php echo $class; ?>"><a href="<?php echo esc_url(get_permalink()); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; wp_reset_query();
?>
</ul>
That's not the proper way to do a menu in Wordpress. 这不是在Wordpress中执行菜单的正确方法。 You should use wp_nav_menu
instead of doing a custom WP_Query
. 您应该使用wp_nav_menu
而不是自定义WP_Query
。
First, in functions.php add the following to register a new menu : 首先,在functions.php中添加以下内容以注册新菜单 :
add_action('after_setup_theme', 'register_my_menu');
function register_my_menu() {
register_nav_menu('skills_menu', __( 'Skills menu', 'your-theme-name' ));
}
Then log in your administration, you will see that new menu placement under Appearance > Menu. 然后登录您的管理,您将在外观>菜单下看到新的菜单位置。 Create a new menu for that placement - you have the possibility to automatically add top level new pages to this menu. 为该展示位置创建一个新菜单-您可以自动将顶级新页面添加到该菜单。
Then in your template add the following in order to display the menu: 然后在模板中添加以下内容以显示菜单:
<?php wp_nav_menu(array('theme_location' => 'skills_menu')); ?>
Wordpress will automatically handle the active class by adding current-menu-item
to the appropriate li
. 通过将current-menu-item
添加到适当的li
Wordpress将自动处理活动类 。 No need for any filter for that. 不需要任何过滤器。
Found an answer for my question using Javascript/jQuery
使用Javascript/jQuery
找到了我的问题的答案
jQuery(document).ready(function($){
var pgurl = window.location.href;
$("ul.skill-items li").each(function(){
if($(this).find('a').attr("href") == pgurl || $(this).find('a').attr("href") == '' )
$(this).addClass("active");
})
});
pgurl
contains your current url. pgurl
包含您当前的网址。 After that for each item we are looking for anchor
and its link. 之后,对于每个项目,我们正在寻找anchor
及其链接。 Then we are comapring those links, and if their are equal, we add class active
to li
然后,我们将这些链接共同映射,如果它们相等,则将active
类添加到li
You may try this: 您可以尝试以下方法:
function my_alter_classes_on_li( $classes, $item ){
global $post;
if( in_array( $post->post_type, $classes ) ) $classes[] = 'current-menu-item';
return $classes;
}
add_filter( 'nav_menu_css_class', 'my_alter_classes_on_li', 10, 2 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.