Style the last post in the WordPress loop differently

I am often asked the question how to style the last post in the WordPress loop differently. There are many occasions when you may want to do this. For example you may have 2 homepage promos and the last right hand item would have a right hand border. Its quite easy to do this quickly in code as show below…

Run the WordPress Query as Normal

$querypromo = new WP_Query( array( 'category_name' => 'Small Homepage Promos', 'orderby' => 'date', 'order' => 'DESC', 'posts_per_page' => '2') );

We then want to set up a counter so we can work out the last post, firstly we declare a variable and set it to 0


We can then run the WordPress Loop as normal and increment a counter

have_posts() ) : $querypromo->the_post(); 
$post_counter++;
?>

We can then use this counter to style the last post in the loop slightly differently:

">

This will result in the the last post having the div class –

You can then continue to add the WordPress code to write out the page as you would do normally. Oh don’t forget to close the WordPress loop! –

You could use CSS to target the last child element (any kind of child element) such as:

#col-1-2 ul li:last-child {
   /* Styling that applies to the last child */
}

However at the moment I am using the coding method to maintain support for older browsers.

I’m sure their are plenty of people who have developed other methods to do this. If so please leave a comment :-)