I want to get the number of products in multiple woocommerce categories considering this fact that each of the categories possess some subcategories. For example:
Category with term_id of 1 have the slug of "organ" and possesses 2 subcategories( "internal" with term_id of 2 and "external" with term_id of 3)
Category with term_id of 4 have the slug of "drug-type" and possesses 2 subcategories( "pills" with term_id of 5 and "capsule" with term_id of 6)
My question is how to get the number of products that are in categories "organ" and "drug-type"?
Edit Version 1:
I tested the following code in my home page and it works and gave me the correct number of products in subcategories of a category with the slug of organ.
$main_product_category = get_term_by( 'slug', 'organ', 'product_cat' );
$main_product_category_id = $main_product_category->term_id;
$args = array(
'hierarchical' => 1,
'show_option_none' => '',
'hide_empty' => 0,
'parent' => $main_product_category_id,
'taxonomy' => 'product_cat'
);
$subcats = get_categories($args);
echo '<div class="quick-search-options">';
foreach ($subcats as $subcat) {
$link = get_term_link( $subcat->slug, $subcat->taxonomy );
echo '<span>
<a href="'. $link .'" class="btn btn-default" data-id="'.$subcat->term_id.'" role="button">'.$subcat->name.$subcat->count.'</a>
</span>';
}
echo '</div>';
Just to make my case more clear to you.
The diagram of my categories is like this:
The number in parenthesis is the number of products in each categories and when I run the above code it will give me correct number for each "internal" and "external" categories.
But when I test it on ajax in only gave me 0 number of products because it only searching for the products that are exactly belonging to the category it self but the weird thing is that the code is not different from the one that I tested in non ajax way.
Any help is appreciated.