I have 3 products having meta key 'check_key' = 1
. 2 of them have attribute 'pa_size_10_20'
with values '100' and '30'; other one have attribute 'pa_size_30_40'
with value '70'.
Please help me understand why the query below returns all 3 products? I expect only 2 products with 'pa_size_10_20' attribute.
$args = array(
'post_type' => 'product',
'visibility' => 'visible',
'post_status' => 'publish',
'numberposts' => -1,
'meta_query' => array(
array(
'key' => 'check_key',
'value' => '1',
'compare' => '='
)
),
'tax_query' => array(
array(
'taxonomy'=> 'pa_size_10_20',
'field' => 'name',
'terms' => 0,
'operator' => '!='
)
)
);
$posts = get_posts( $args );
TIA
My Answer:
'product',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'check_key',
'value' => '1',
'compare' => '='
)
),
'tax_query' => array(
array(
'taxonomy' => 'pa_size',
'field' => 'slug',
'terms' => array('10-20'),
'operator' => 'IN'
)
)
);
$query = new WP_Query($args);
The issue with your query is that you are using the 'tax_query' parameter to query for products with a specific attribute ('pa_size_10_20'), but you are using the wrong taxonomy name. The correct taxonomy name for attributes in WooCommerce is 'pa_size' followed by the attribute name.
In your case, the correct taxonomy name should be 'pa_size_10_20' instead of just 'pa_size'. So your 'tax_query' parameter should be updated as follows:
'tax_query' => array(
array(
'taxonomy' => 'pa_size_10_20',
'field' => 'slug',
'terms' => array('100', '30'),
'operator' => 'IN'
)
)
With this change, the query should only return the 2 products with the 'pa_size_10_20' attribute and values '100' and '30'.
Rate this post
3 of 5 based on 4299 votesComments