Here’s what I come up with, looks like it’s working. But maybe (surely) there’s a more efficient way to do the same:
// current queried
$term = 'sector';
$current_sector_id = get_queried_object_id();
// Prepare wp_query to get all posts assigned to the current "sector"
$sector_posts_query = new WP_Query();
$sector_posts_query->query(
array(
'post_type' => 'post',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => $term,
'field' => 'term_id',
'terms' => $current_sector_id
),
)
)
);
// loop the posts
if ($sector_posts_query->have_posts()) {
$terms_array = array();
while ($sector_posts_query->have_posts()) : $sector_posts_query->the_post();
// get the product_cat of each post and store it as arrays in the $terms_array
$current_category_terms = get_the_terms(get_the_ID(), 'my_category');
$terms_array[] = wp_list_pluck($current_category_terms, 'term_id');
endwhile;
wp_reset_postdata();
}
// merge the inner arrays and remove doubles
$result = call_user_func_array("array_merge", $terms_array);
$result = array_unique($result, SORT_REGULAR);
echo '<ul>';
foreach ($result as $id) {
$my_category = get_term_by('id', $id, 'my_category');
$my_category_url = get_term_link($id, 'my_category');
echo '<li><a href="' . $my_category_url . '">' . $my_category->name . '</a></li>';
}
echo '</ul>';