How do you get the count of posts in an archive page?

I have a custom posts archive page of the type archive-my_custom_post_type.php and I am using the “standard” loop which consists of the ever-so famous

<?php if(have_posts()) : ?>
    <?php while(have_posts()) : the_post(); ?>
        ...
    <?php endwhile;  ?>
<?php endif; ?>

Which seems to use global variables.

Read More

How would I go about getting the total amount of posts for this page? I need it to calculate the width of the columns I’m going to display these things in.


Well, I found the answer:


After some tedious inspection on the $GLOBALS variable in PHP, I found out you can get a reference to the WP_Query that was used to generate the page with $wp_the_query. And, lo and behold, you can get the amount of posts using this handy trick:

$countPosts = $wp_the_query->post_count;

Hope this helps anyone who has the same problem I had!

Related posts

1 comment

  1. As stated in the edit:

    $count = $GLOBALS['wp_query']->post_count;
    

    Another option would be to use

    $count = $GLOBALS['wp_query']->found_posts
    

Comments are closed.