Home Forums General Issues Add "current" class to list of related posts


Add "current" class to list of related posts

  • Hi all,

    I have a field group called Lessons, and within each lesson, I list all related lessons.

    Everything displays perfectly using this from the documentation:

    <?php foreach( $posts as $post): ?>
      <?php setup_postdata($post); ?>
        <li class="lesson">
          <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
    <?php endforeach; ?>

    How can I adapt this so if I’m on the page “Lesson 1”, Lesson 1 in the displayed list has its own “current” class so I can style it?

    (I essentially want this to act the same as WP’s navigation does when on the current page)

  • Hi @barron

    I’ve written some code for you to show how you would compare the current ID to the loop ID:

    <?php foreach( $posts as $post): ?>
        <li class="lesson <?php if( get_the_ID() == $post->ID): ?>active<?php endif; ?>">
          <h3><a href="<?php echo get_permalink( $post->ID ); ?>"><?php echo get_the_title( $post->ID ); ?></a></h3>
    <?php endforeach; ?>

    Please note I have removed the setup_postdata function as this will only cause you headaches if you are not careful with it

  • @elliot

    Thanks for such a quick reply. Looks like we’re close (as in, everything technically works), but when using your code exactly, the active class is being applied to all li.

    Suggestions for adjustments?

  • Hi @barron

    Perhaps you need to store the $post_id outside of the loop. Also, check that it is the expected value.

    Then change the conditional logic within the loop to compare against the variable

  • I had to do a bit more searching but your suggestion sent me in the right direction, so thanks @elliot

    Here was my final code:

    	global $post;
    	$the_post_ID = $post->ID;
    <?php foreach ( $posts as $post ) : ?>					
    	<li<?php if ( $post->ID == $the_post_ID ) echo ' class="current"'; ?>>
    	    <h3><a href="<?php the_permalink(); ?>" title="<?php echo get_the_title( $post->ID ); ?>" rel="bookmark"><?php the_title(); ?></a></h3>
    <?php endforeach; ?>
Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Add "current" class to list of related posts’ is closed to new replies.