I'm overriding wpseo_title to make custom titles for my Woocommerce product categories.

Part of the titles are the number of products, based on $product_category->count

The only problem is that count of subcategory products isn't included. It's only the products in the category itself that are counted.

Is there a way to get the product count for the category itself + its subcategories?


WP_Query can be used to determine the number of posts contained within a category and its subcategories.

In the code below, set the terms parameter to whatever the parent category ID is. The include_children parameter ensures that WP_Query will include posts within subcategories.

We can then use $query->post_count to get the total number of posts in the parent category and its subcategories.

$query = new WP_Query( array(
    'tax_query' => array(
            'taxonomy' => 'product_cat',
            'field' => 'id',
            'terms' => 79, // Replace with the parent category ID
            'include_children' => true,
    'nopaging' => true,
    'fields' => 'ids',
) );

echo '<p>Total product count: <strong>' . esc_html( $query->post_count ) . '</strong></p>';
| improve this answer | |
  • +1 but it probably flies way too high over the head of most readers ;) some explanation is probably needed – Mark Kaplun Feb 25 '18 at 16:28
  • @MarkKaplun Good call on adding an explanation. All set! – Dave Romsey Feb 25 '18 at 20:33

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.