0

Hi there I'm using the following query to pull in two featured posts onto the home page of a site I'm building. How do I add a last class to the second post it drops onto the page?

                <h3>Case Studies</h3>
            <?php $my_query = new WP_Query('post_type=casestudy&posts_per_page=2');
                while ($my_query->have_posts()) : $my_query->the_post();
                $do_not_duplicate = $post->ID; ?>
                <div class="half">
                    <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a>
                    <p class="home-news-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
                    <?php the_excerpt(); ?>
                </div>
                <?php endwhile; ?>

Thanks John

2

There are a few ways you could do it involving incrementing and checking a counter variable. I prefer to use the built-in member vars present in the main and every custom WP_Query.

This will give you the index of the current post in the loop:

$my_query->current_post

Just remember that it's zero indexed, meaning the first post is 0, second is 1, etc..

and this will give you the number of posts returned from your query:

$my_query->post_count

so we just combine those in an if statement to check if it's the last post in the loop. Remember to add 1 to current post here because it starts at zero:

while ($my_query->have_posts()) : $my_query->the_post();

    $class = 'half';
    if( ( $my_query->current_post + 1 ) == $my_query->post_count ){
        $class .= ' last';
    }

    echo '<div class="' . $class . '">';
    // rest of your markup, etc..

endwhile;
2

Check $my_query->current_post and you can easily determine which post you are on. I used that to set the post class and then used the post_class function to insert that class and all of the defaults.

<h3>Case Studies</h3>
<?php $my_query = new WP_Query('post_type=post&posts_per_page=2');
  while ($my_query->have_posts()) : $my_query->the_post();
    $do_not_duplicate = $post->ID; 
    $new_class = (1 === $my_query->current_post) ? 'half' : '' ?>
    <div <?php post_class($new_class); ?>>
      <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a>
      <p class="home-news-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
      <?php the_excerpt(); ?>
    </div>
<?php endwhile;

Note that *->current_post starts indexing at 0 so 1 is the second post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.