Add ‘last’ class to second post in featured post loop

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;