Issue
I am trying to apply filters in a list of products. Users will use select boxes on the front end and click a button to filter the products.
Every product is it's own post, so I use WP_Query to get the posts. For example, I want all products with the color "red", the material "plastic" and the brand "Bikon". So I use;
$color = "red";
$material = "plastic";
$brand = "Bikon";
$query = new WP_Query(array(
'post_type' => 'products',
'posts_per_page' => 6,
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => $color,
'compare' => '='
),
array(
'key' => 'material',
'value' => $material,
'compare' => '='
),
array(
'key' => 'brand',
'value' => $brand,
'compare' => '='
)
)
));
And this will work fine if every value get's set. But if only one of the select boxes is used, the other two values will be empty and the query will not return any posts. Is there any way to say "only use this array in the meta query if this value is set"?
Solution
You can check for definition of variable and add additional filtering if it exists
$query_args = array(
'post_type' => 'products',
'posts_per_page' => 6,
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'product_check',
'compare' => 'EXISTS',
),
),
);
if(isset($color) && $color) {
$query_args['meta_query'][] = array('key' => 'color', 'value' => $color, 'compare' => '=');
}
if(isset($material ) && $material ) {
$query_args['meta_query'][] = array('key' => 'material ', 'value' => $material , 'compare' => '=');
}
if(isset($brand ) && $brand ) {
$query_args['meta_query'][] = array('key' => 'brand ', 'value' => $brand , 'compare' => '=');
}
$query = new WP_Query($query_args);
Answered By - Alexey Svidentsov Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.