10

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.

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!

2
  • 5
    You can put your answer in the answer box below your question and also mark this question as solved :)
    – Sven
    Feb 14, 2014 at 9:58
  • 1
    Next time look at Codex it's far from perfect, but sometimes it's helpful :)
    – gmazzap
    Feb 15, 2014 at 3:50

1 Answer 1

18

As stated in the edit:

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

Another option would be to use

$count = $GLOBALS['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.