0

I am attempting to find related custom post types that share at least one term in taxonomy A and at least one term in taxonomy B. So it is sort of taxonomy A AND taxonomy B but OR within the terms of these taxonomies. What I have below brings 0 results, even though it should.

"tax_query" => array(
              'relation' => 'AND',
                array(
                   'taxonomy' => 'values',
                   'field' => 'term_id',
                   'terms' => $values_array
                ),
                array(
                    'taxonomy' => 'product_type',
                    'field' => 'term_id',
                    'terms' => $product_type_array
                )

      )

This here below where I've added "or" pulls all posts of that type regardless of taxonomy terms:

"tax_query" => array(
              'relation' => 'AND',
                array(
                   'taxonomy' => 'values',
                   'field' => 'term_id',
                   'terms' => $values_array,
                    'operator' => 'OR'
                ),
                array(
                    'taxonomy' => 'product_type',
                    'field' => 'term_id',
                    'terms' => $product_type_array,
                    'operator' => 'OR'
                )

      )

EDIT: was asked for more context on how the $values_array and $product_type_array were built. Below is what happens prior to the query to build these:

$post = get_post();
$post_type = get_post()->post_type;
$post_id = get_post()->ID;
$values = wp_get_post_terms($post_id, 'values');
$product_types = wp_get_post_terms($post_id, 'product_type');

$product_type_array = [];

foreach($product_types as $product_type){
    array_push($product_type_array, $product_type->term_id);
}

$values_array = [];

foreach($values as $value){
    array_push($values_array, $value->term_id);
}
  • where do you set $values_array and $product_type_array? – Milo Jan 19 at 21:06
  • Hello! I've added a new codeblock to the question to show how these are built. – Emge Jan 19 at 22:57
  • I figured this out! So nevermind. I had two terms with the same name, so when I was sure a certain post should pull another that had the same term it was actually a different term in the database. Derp. Nothing to do with the query. – Emge Jan 19 at 23:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.