There’s probably a few ways to do this. The key will be cutting down on the number of loops you need to make it more efficient.
I think this will work:
$query = new WP_Query( array(
'post_type' => 'product',
'posts_per_page' => '-1', // unlimited posts
'tax_query' => array(
array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => array( 'tag1' ),
),
),
) );
$categories = array();
while( $query->have_posts() ){
$query->the_post();
$post_categories = get_the_terms( $post, 'product_cat' );
foreach( $post_categories as $_cat ){
if( ! isset( $categories[$_cat->term_id] ) ){
$categories[$_cat->term_id] = $_cat;
}
}
}
wp_reset_postdata();
foreach ($categories as $category){
echo $category->name . '<br />';
}
This is completely untested and rather quickly put together, but I think it should do what you want. You’ll need to replace product_cat
and product_tag
with the correct taxonomy names if those aren’t right (I don’t use WooCommerce regularly).
Basically, using a tax_query
, we’re first finding all the posts that have the required tag. We then loop through those posts and construct a list of categories, finally looping through those categories to print them out.
This results in a list of categories that contain products with that specific tag.