Counting the posts of a custom WordPress loop (WP_Query)?

I tried tplacing this:

    <?php $count = count($custom_posts); ?>
    <h2><?php echo $count; ?></h2>

at the end of the loop:

      <?php if ( bbp_get_forum_title() == 'Test Forum 1' ) : ?>
            <?php $custom_posts = new WP_Query(); ?>
            <?php $custom_posts->query('post_type=blocks&location=Business and Finance&order=DESC'); ?>
            <?php while ($custom_posts->have_posts()) : $custom_posts->the_post(); ?>
                <div class="ad">
                    <?php the_content(); ?>
                </div>
                <?php $count = count($custom_posts); ?>
                <h2><?php echo $count; ?></h2>
            <?php endwhile; ?>
      <?php endif; ?>

But instead of the total of posts, I getting this output:

Translation 1

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat
volutpat. Ut wisi enim 1

Any suggestions to fix this?

3

Correct way of getting the total number of posts is:

<?php $count = $custom_posts->found_posts; ?>

http://codex.wordpress.org/Class_Reference/WP_Query#Properties

Edit: acknowledging @Kresimir Pendic’s answer as probably correct. post_count is the count of posts for that particular page, while found_posts is the count for all available posts that meets the requirements of the query without pagination. Thank you for the correction.

Leave a Comment