I was recently asked if it was possible to make the last post displayed in the loop of a WordPress blog different. I thought it would make a good tutorial, so here is how it’s done.

Changing the last post displayed in the loop isn’t really that difficult if you have knowledge of the variables available inside $wp_query. However changing the last post, only if it is truly the last post, is a lot more difficult.

What Do You Mean? Truly The Last Post?

A lot of tutorials show you how to change the last post displayed on the current page, meaning that on each page (if your loop is paginated) your last post will be different. What I was asked though was just to change the last post, by that I mean the last post on the last page. For example if a query returns 30 posts I only want to change the 30th post, not the 10th, 20th & 30th (assuming 10 posts are displayed per page).

Ahh. How Do You Do It Then?

Well first, let’s take a look at what you might use it for.

Change Last Loop Item WordPress

As you can see, it has been used to promote the ability to visit another website where more products are available. Thanks to Lisa Marie for the image.

So how is it done I hear you cry. Well it’s done using some variables held inside $wp_query and some fairly simple Math. Let’s take a look at the code.

if(((($wp_query->query_vars['paged'] - 1) * $wp_query->query_vars['posts_per_page']) + ($wp_query->current_post + 1)) == $wp_query->found_posts) {
    //Whatever you want to occur should this be the last post
}

Okay. I know it looks confusing, but let’s break this down. The sum is bracketed to control how the computer completes the sum, so let’s do it in order.

First we take the current page number ($wp_query->query_vars['paged']) minus one to give us the number of the previous page, we then multiply that by the number of posts per page ($wp_query->query_vars['posts_per_page']).

Then we take the current post number ($wp_query->current_post) and add one to it.

Now we take the result from the first set of sums (paragraph 1) & the second set of sums (paragraph 2) and add them together. Then check if that is equal to the number found in $wp_query->found_posts which contains the number of posts found for the query in total.

Is That All?

Yes, believe it or not, that’s it. If you want to change the last post on each page the code would instead be:

if(($wp_query->current_post + 1) == $wp_query->post_count) {
    //Whatever you want to occur should this be the last post of the current page
}

That code is available all over the place, but I thought I’d put it here for reference sake.

I hope this tutorial has helped you in some way. If you have any questions about anything in this post please leave a comment below & I’ll answer as soon as I can. Also please don’t forget you can follow me on Twitter or if you want to help us out you can donate using the link in the box below this post.