custom taxonomy - Query Multiple Taxonomies and Multiple Terms with Different Operators

admin2025-06-04  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);
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748994341a315459.html

最新回复(0)