I'm trying to get a count of the current posts inside of a loop. I'm using multiple loops on one page in my theme. So far I have:

$my_post_count = $wp_query->post_count;

But when I print $my_post_count, it returns the number all of the posts on my WP site. Could it have something to do with using multiple queries on one page? I tried using wp_reset_query after every loop to make sure I wasn't throwing things off that way. What am I doing wrong?

4 Answers 4


$wp_query hold main loop of page and should not be used to create multiple loops.

If you are using new WP_Query object then your variable that holds it will have according count:

$my_query = new WP_Query();
// stuff
$count = $my_query->post_count;

If you are using get_posts() then WP_Query object is not accessible and you should just count returned set:

$posts = get_posts();
$count = count($posts);
  • 1
    Note: If you are in the main loop, you can access WP_Query through global $wp_query
    – mrmadhat
    Oct 22, 2019 at 8:45

I believe the post_count is stored in the global, so before the custom loop you should set it to 0, since you can use it outside the loop, but this depends on how you are structuring your multiple query's, maybe you can add them to your post?

There is another way that I use within the loop that counts posts using current_post + 1, for example.

<?php $my_query = new WP_Query();?>
     <?php if ($my_query->have_posts()) :while ($my_query->have_posts()) : $my_query->the_post();

           $count_posts = $my_query->current_post + 1; //counts posts in loop


An alternative solution using WP_Query would be:

               $args = array(
               'post_type' => 'post'
            $the_query = new WP_Query( $args );
            $totalpost = $the_query->found_posts; 

Simple way to count total post including pagignation

<?php  global $wp_query
   echo $wp_query->found_posts; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.