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


Add "current" class to list of related posts

    • barron

    • August 20, 2013 at 2:05 pm

    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)

    • Elliot

    • August 20, 2013 at 3:05 pm

    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

    • barron

    • August 20, 2013 at 3:32 pm


    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?

    • Elliot

    • August 21, 2013 at 2:06 pm

    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

    • barron

    • August 21, 2013 at 3:32 pm

    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)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.