Menu

How to detect the last post in the WordPress loop

Sometimes you want to style only the last post in a WordPress loop or you may want to add a comma at the end of every post except the last one. Here’s an example of how to do that:

<?php if (($wp_query->current_post +1) == ($wp_query->post_count)) {
echo 'This is the last post';
} ?>
<?php if (($wp_query->current_post +1) != ($wp_query->post_count)) {
echo 'This is the not the last post';
} ?>