Show number of posts out of total records in WordPress

From time to time, I just look at my blogs and see what I can add to it to make it more appealing to the user. I’ve always admired those sites that tell you what number of posts a certain category has, and what number of posts it is currently showing. So I set out to do just that.
Since I haven’t written anything WordPress related for a while, I figured this would be good practice. What we’re writing is something like below:
numposts1
You see, we want to show what posts are currently showing – out of how many total records. It’s not a hard task – since all we really need are 2 variables: the current total showing and the total number found.

The $wp_query Object

According to the codex, the WP_Query class “deals with the intricacies of a post’s (or page’s) request to a WordPress blog”. This means that WordPress has already done the heavy lifting when it comes to information needed when you query your posts. Information needed when building stuff like paging, queries, templates and meta data.
In our case, we need the meta data – of the posts returned. So first off, open the index.php file in your theme directory and just outside the loop, add the code below:

print_r($wp_query);exit;

What we’re doing is seeing what the $wp_query is holding. $wp_query is the object that is derived from the WP_Query class that we talked about above. You will see a long array of information that pertains to the current request. So say you’re in a certain category, this object will contain information about that category and the posts that it contains.
So somewhere in this object lies the information we need. Let’s grab “post_count” and “found_posts”.
numposts2
Now that we know the property names, we can go ahead and remove the print_r that we have.

The Output

This is as simple as it gets. All we need is to check if “post_count” is more than 0 and we can echo out our sentence. We can hard code the “1” since we’re always going to be showing at least 1 record.


    Showing 1 through  out of  articles..

The code above should work anywhere in your theme. It’s especially useful in your archive templates – so users can tell how many articles are in a specific category etc. It’s a good addition to your paging in the footer as well.
To test it, try searching for something, or click on a category. The “found_posts” should depend on the current request, while the “post_count” depends on the limit that you have in your WordPress settings.
And that’s it. Hopefully you can find this snippet useful in your theme somewhere. Please leave your comments below.

1 Comments

Leave a Comment.