0

I have a list of sub-menus in the page which will get the title of each article. But I hope the list style will be different from others when it is in the specific article page.

Now the <a> tag has only a class named "list-group-item", and I hope there will be another "active" class added in the <a> tag when it is in the article.

Hope someone could help me to solve this...thank you in advance.

Here is my codes:

<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();?>
Ruvee
  • 8,611
  • 4
  • 18
  • 44
Terry Chan
  • 41
  • 2
  • 10

2 Answers2

1

You can use get_the_ID() to get the ID of the current post page you're visiting and add an additional class active-item if it matches the post ID you're querying in the foreach loop:

 <?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; ?>
xphan
  • 1,038
  • 6
  • 8
0

You can use

<?php the_title();?> 

in condition for current article title and add active class like this :

<?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>
Lalji Nakum
  • 380
  • 1
  • 14