WooCommerce product category count
Asked Answered
U

1

6

I'm creating a filter widget to show WooCommerce products followed by product count for the category, and it will also work when search string exists.

Like, These three categories,

  1. Laptops (5),
  2. Desktops (7),
  3. Tablets(12)

Now, if someone searches for Asus then there are 2 Laptops, 4 Desktops and 7 Tables match for Asus.

Now, In sidebar, per category will show how many products matches on the category for the search.

Currently, I am showing the counter by Default WP_Query with the tax_query parameter but it seems very slow, because if there are 50 categories, the query runs 20 times. I believe there is a better way to do this.

Can someone help me to find some easier way?

Unbend answered 30/1, 2016 at 12:47 Comment(4)
what is your current code for displaying this?Muntjac
$args["tax_query"]= array( array( 'taxonomy' => 'product_cat', 'terms' => $terms, 'include_children' =>true ), );Unbend
how are you displaying the categories?Muntjac
Using get_terms( ) functionUnbend
S
1

You can get counts by terms :

$terms = get_terms('product_cat', ['hide_empty' => false]);

foreach($terms as $term){
 echo "{$term->name} ({$term->count})"
}

If you want to take only parent categories you can do it like this

$terms = get_terms('product_cat', ['hide_empty' => false, 'parent' => 0]);

Southeast answered 29/11, 2021 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.