Counting the posts of a loop (WP_Query)?

Some additional information, no need to count the posts again, because WP_Query already did that for you. To clarify this, some information from the Class Reference of WP_Query as found in the »Properties« section:

$post_count
The number of posts being displayed.

$found_posts
The total number of posts found matching the current query parameters

What this means is

  1. $post_count won’t give you the total post count. It will most likely give you the number of posts you’ve defined with the post_per_page parameter, unless you’ve fewer posts than that or you’re on the last page and there are only fewer posts left.
  2. $found_posts can be used to get the total number of post related to a specific query. So there is no need to count them again.

In your case you can get the total count into your $count variable like this:

$count = $news_2->found_posts;

Besides of that @helgatheviking is right that, from what you’ve shown in your question, you don’t need a extra conditional, but can just use the have_posts() method, in the conditional you already have, for that, like she suggested.

Leave a Comment