I am trying to make a simple form to query woocommerce products wine based on form input fields as follows:
Selected category (Vine type, eg. red wine, white wine etc..) - Input type dropdown
Select Winery Tag 1 dropdown
Select Wine Sort Tag 2 dropdown
Select wine region Tag 3 dropdown
Price Range dropdown
Filtering by category and price works, however tags give mixed results and i cannot figure out why.
This is how my form looks like to give some context:
Here is my code:
$custom_query_args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'order' => 'DESC',
'posts_per_page' => 3,
'product_tag' => array($tag1, $tag2, tag3),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => array( esc_attr( $category ) ),
'field' => 'slug',
'operator' => 'OR'
)),
//Price
'meta_query' => array(
array(
'key' => '_price',
'value' => array($clow, $chigh),
'compare' => 'BETWEEN',
'type' => 'NUMERIC'
)
)
);
From the input fields, I have 3 variables for product tags (like $tag1
, $tag2
, $tag3
), 1 variable for product category (like $category
) and 2 variables for the price range (like $clow
and $chigh
) which are the price from to.
Anyone have an idea why this happens?
There are some little mistakes in your code:
$
in tag3
,OR
is not an operator
value (and it's not needed),tax_query
array to get your filters working.So try the following modified code instead:
$custom_query_args = array(
'posts_per_page' => 3,
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'order' => 'DESC',
'tax_query' => array(
// Product category filter
array(
'taxonomy' => 'product_cat',
'terms' => array( esc_attr( $category ) ),
'field' => 'slug',
),
// Product tag 1 filter
array(
'taxonomy' => 'product_tag',
'terms' => array($tag1),
'field' => 'slug',
),
// Product tag 2 filter
array(
'taxonomy' => 'product_tag',
'terms' => array($tag2),
'field' => 'slug',
),
// Product tag 3 filter
array(
'taxonomy' => 'product_tag',
'terms' => array($tag3),
'field' => 'slug',
),
),
// Price filter
'meta_query' => array( array(
'key' => '_price',
'value' => array($clow, $chigh),
'compare' => 'BETWEEN',
'type' => 'NUMERIC'
) ),
);
Tested and works.