I needed something similar. This is what I did:
$args = array(
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => get_query_var('taxonomy'),
'field' => 'slug',
'terms' => get_query_var('term'),
)
),
);
$products = new WP_Query($args);
$attributes = array();
while ($products->have_posts()) : $products->the_post();
$post_atts = get_the_terms(get_the_ID(), 'pa_' . $attr);
if ($post_atts) {
foreach ($post_atts as $x) {
if(!in_array($x, $attributes)){
$attributes[]=$x;
}
}
}
endwhile;
print_r($attributes1);
This code is written for product and attributes, so you’ll have to modify it for your need.