List custom taxonomy terms sharing posts with a term from a second custom taxonomy

I’m not sure if it’s possible to directly query the terms, So I’m gonna write a workaround for you.

The WP_Query(); accepts an argument named terms. You can pass term IDs as an array to this argument.

Let’s first fetch a list of terms in the first taxonomy, then query based on these terms:

$terms = get_terms( 
    array(
       'taxonomy'   => 'custom_tax1',
       'hide_empty' => false,
       'fields'     => 'ids', // We only need the IDs
   )
);
// Now do a query
$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'custom_tax2',
            'field'    => 'slug',
            'terms'    => $terms,
        ),
    ),
);
$my_query = new WP_Query( $args );

This will query every post from custom_tax2 that has any of the terms from custom_tax1. Now that you have the posts that have these terms, you can proceed with extracting terms from them.

Let’s crack this down a bit further:

if($my_query->have_posts()){
    // Define an empty array to use later
    $post_terms = array();
    while($my_query->have_posts()){
        $my_query->the_post();
        // Merge the previous terms with the new ones
        $new_terms = wp_get_post_terms( get_the_ID(), 'custom_tax1');
        $post_terms = array_merge( $post_terms, $new_terms );
    }
}

Here is what happened.

  1. We run a loop through all the posts belonging to custom_tax2 taxonomy that have the terms from custom_tax2 taxonomy.
  2. We get the terms of every post in the loop
  3. On each step of the loop we merge the current terms with terms from the previous post, so we end up with an array of terms from each post