Target second from last post in loop

For featured posts rendering in rows of three, I have a total of 5 featured posts to work with. Three of five posts render in-line center but the remaining two float:left inline beneath the top three. I want the remaining two centered below the top three. I could use CSS and assign margin-left: to the second-to-last post, but when customer adds another post to the loop, a new second-to-last post is pushed into position within the featured-posts container. That new second to last post doesn’t have the proper CSS.

The following allows the targeting of the last post in the loop and it works great if the total number of featured posts is ten. Ten posts allows for a last single post below all others (all previous nine rendering in rows of three). I can accomplish the centering of the last post by assigning a custom template_part (I’m using an _s theme)

How do I target the second to last post instead of the last post with the query below?

$prelimartPosts = new WP_Query($args2);

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

 if (($prelimartPosts->current_post +1) == ($prelimartPosts->post_count)) {

    get_template_part( 'template-parts/content', 'front-center' );


 if (($prelimartPosts->current_post +1) != ($prelimartPosts->post_count)) {

    get_template_part('template-parts/content', 'front-bottom');



See here. Scroll to bottom of page under “PRELIMINARY ART“:

Read more here: Target second from last post in loop

Leave a Reply

Your email address will not be published. Required fields are marked *