I have code that successfully returns product within a price range. However, I need to also filter by a product attribute called 'size'.
So I should get all products of a certain size between the given price range.
My code works for the price range part, but I can't work out the correct way to add the size part.
Here's my code:
$params = array(
'posts_per_page' => 20,
'post_type' => array('product', 'product_variation'),
'meta_query' => array(
'relation' => 'AND',
array(
array(
'key' => '_price',
'value' => $_POST['product_price_min'],
'compare' => '>=',
'type' => 'NUMERIC'
),
array(
'key' => '_price',
'value' => $_POST['product_price_max'],
'compare' => '<=',
'type' => 'NUMERIC'
)
),
array(
array(
'taxonomy' => 'pa_size',
'field' => 'slug',
'terms' => $_POST['size'],
'operator' => 'IN',
)
)
)
);
$products = new WP_Query($params);
I have code that successfully returns product within a price range. However, I need to also filter by a product attribute called 'size'.
So I should get all products of a certain size between the given price range.
My code works for the price range part, but I can't work out the correct way to add the size part.
Here's my code:
$params = array(
'posts_per_page' => 20,
'post_type' => array('product', 'product_variation'),
'meta_query' => array(
'relation' => 'AND',
array(
array(
'key' => '_price',
'value' => $_POST['product_price_min'],
'compare' => '>=',
'type' => 'NUMERIC'
),
array(
'key' => '_price',
'value' => $_POST['product_price_max'],
'compare' => '<=',
'type' => 'NUMERIC'
)
),
array(
array(
'taxonomy' => 'pa_size',
'field' => 'slug',
'terms' => $_POST['size'],
'operator' => 'IN',
)
)
)
);
$products = new WP_Query($params);
Share
Improve this question
asked Mar 21, 2019 at 17:24
benhen31benhen31
54 bronze badges
1
- stackoverflow/questions/44688846/… – rudtek Commented Mar 21, 2019 at 17:38
1 Answer
Reset to default 1Your mixing up your meta query and tax query. try this:
$params = array(
'posts_per_page' => 20,
'post_type' => array('product', 'product_variation'),
'meta_query' => array(
array(
'key' => '_price',
'value' => $_POST['product_price_min'],
'compare' => '>=',
'type' => 'NUMERIC'
),
array(
'key' => '_price',
'value' => $_POST['product_price_max'],
'compare' => '<=',
'type' => 'NUMERIC'
),
),
'tax_query' => array(
array(
'taxonomy' => 'pa_size',
'field' => 'slug',
'terms' => $_POST['size'],
'operator' => 'IN',
)
)
);
$products = new WP_Query($params);