Get terms that are associated with products from current category

Question

I need to list all custom terms (brands) that are associated with products from the category that is currently being viewed. E.g. I have these brands created:

  • Shirt Brand A
  • Shirt Brand B
  • Shirt Brand C
  • Jeans Brand A
  • Jeans Brand B

On ‘Shirts’ category page, only Shirts Brands A, B and C are displayed.

This is how I did it:

$args = array(
    'taxonomy' => 'brand',
    'orderby' => 'count',
    'order' => 'DESC',
    'hide_empty' => false
);
$brands = get_terms($args);

foreach($brands as $brand) {
    if(is_product_category()) {
        $cat_id = get_queried_object_id();
        $count_args = array(
            'post_type'             => 'product',
            'post_status'           => 'publish',
            'tax_query'             => array(
                array(
                    'taxonomy'      => 'product_cat',
                    'field'         => 'term_id',
                    'terms'         => $cat_id,
                    'operator'      => 'IN'
                ),
                array(
                    'taxonomy'      => 'brand',
                    'field'         => 'slug',
                    'terms'         => $brand->slug,
                    'operator'      => 'IN'
                )
            )
        );
        $count_products = new WP_Query($count_args);
        if($count_products->post_count <= 0) continue; // Skip if this query contains zero products

        // Display brand that has at least 1 product in this category
        display_brand();
    }
}

Of course it works, however with 300+ brands created it sometimes takes 0,5 – 1,5 seconds for this loop to get processed, which is unnecessary lot. AFAIK there is no direct database relation between terms and product categories (only number of posts for each term), but is there a better way to do this with better performance?

0
Kristian Filo 4 months 0 Answers 16 views 0

Leave an answer