• So, I have a WordPress site with a bunch of Categories. But, I want to FETCH and Display the Total Post count for every Category.

    Let’s say I have a Category Books, with 15 posts.

    I want to display the total number of posts in the Category => Books.

    Ex. 15 Books

    • This topic was modified 2 years, 7 months ago by forestrify.
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    You can make a new WP_Query object, passing args to get some posts that you need a total count of. The object has a $found_posts property, which is not the same as the posts per page count of the posts actually returned by the query. $found_posts is the number of all posts in the DB matching the query criteria. You can make such a query directly from template code, echoing out the value of $found_posts.

    $query = new WP_Query(['category_name' => 'books',]);
    echo $query->found_posts;

    If the template is for listing posts in the same category, you can use the existing WP_Query object’s properties. The existing object is in global $wp_query.

    Thread Starter forestrify

    (@forestrify)

    Thank you very much for your input.

    But I need the function to be applied to all categories, and not just one. So, there’s no point in specifying a particular category.

    How can I achieve that, please?

    Moderator bcworkz

    (@bcworkz)

    If you stay with WP methods, it’ll be cumbersome. You’d get a list of all categories, then loop through the list, making a count query for every category.

    To get counts within every category, all in one go, you’d need a custom SQL query that uses GROUP BY to get a summary count of posts assigned each category term. You can execute custom queries using wpdb class methods with the global object $wpdb. I’m not very good with SQL, so I cannot provide an example. It does involve JOINing in term_relationships and term_taxonomy tables along with the use of GROUP BY.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Count Posts In WordPress Category’ is closed to new replies.