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(); ?>
                    <?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?

  • Correct way of getting the total number of posts is:

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

    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.

    Thanks! Hey one last question. How can I use that number to make an if statement which is out of that loop (before of the loop). Because it seems like the number is only displayed when I place the variable after that loop.

    You can put the $count = $custom_posts->post_count just after the $custom_posts->query(). Note that $custom_posts->post_count only gets you the number of results in that 'page' of the result set. If you need to get the total number of results in the 'whole' result set, use $custom_posts->found_posts.

    This answer is most likely not correct for most situations. Use found_posts (all found posts) instead of post_count (number of posts to display on this page). This comment is redundant logically speaking, but not socially speaking.

    This answer is incorrect. `$custom_posts->post_count` will return the amount of posts shown on this page, so it will display either the `posts_per_page` value of the query or a lower value if the amount remaining to show is lower. the correct answer should be `<@kresimir-pendic>`'s answer that uses `$custom_posts->found_posts`

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM