【问题标题】:How to add active class in wordpress submenu?如何在 wordpress 子菜单中添加活动类?
【发布时间】:2021-09-14 21:45:10
【问题描述】:

我在页面中有一个sub-menus 列表,它将获得每篇文章的标题。 但我希望列表样式在具体文章页面时与其他样式有所不同。

现在<a>标签只有一个名为“list-group-item”的类,我希望文章中的<a>标签中再添加一个“活动”类。

希望有人能帮我解决这个问题...提前谢谢你。

这是我的代码:

<div class="list-group">
 <?php global $post;
   global $all_post_titles;
   $all_post_titles = array();
   $args = array('post_type' => 'service','orderby' => 'ID','order' => 'ASC',);
   $myposts = get_posts( $args );
     foreach( $myposts as $post ) :  setup_postdata($post);?>
         <a href="<?php the_permalink(); ?>" class="list-group-item"><?php the_title();?> <span class="fa fa-angle-right"></span></a>
     <?php endforeach; ?>
  <?php wp_reset_postdata();?>

【问题讨论】:

    标签: wordpress wordpress-theming custom-wordpress-pages wp-nav-menu-item


    【解决方案1】:

    您可以使用 get_the_ID() 获取您正在访问的当前帖子页面的 ID,如果它与您在 foreach 循环中查询的帖子 ID 匹配,则可以添加一个额外的类 active-item

     <?php 
     // get the ID of the current post
     $current_id = get_the_ID(); 
     ?>
     <?php foreach( $myposts as $post ) :  setup_postdata($post);?>
         <a href="<?php the_permalink(); ?>" class="list-group-item<?php echo ($post->ID==$current_id?' active-item':''); ?>"><?php the_title();?> <span class="fa fa-angle-right"></span></a>
     <?php endforeach; ?>
    

    【讨论】:

      【解决方案2】:

      你可以使用

      <?php the_title();?> 
      

      在当前文章标题的条件下并添加这样的活动类:

      <?php 
           $activeclass="";
           if(the_title()== $post->name)
           { 
               $activeclass="active";
           }
       ?>
       <a href="<?php the_permalink(); ?>" class="list-group-item "><?php the_title();?> <span class="fa fa-angle-right <?php echo $activeclass; ?>"></span></a>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-30
        • 2020-03-20
        • 2017-09-11
        • 2015-08-05
        • 2013-12-04
        • 2021-08-14
        • 2016-06-24
        相关资源
        最近更新 更多