I am using WP_Query for visitor to filter the posts. The posts is about products. So in the filter, it has a field where user can select Maximum price and Minimum price. (Just like most of the shopping site).
Okay this is the filter form that I use to collect the user input:
<lable>Min. Price ($)</lable>
<select name="minprice">
<option value="0">0</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="300">300</option>
.....
</select>
<lable>Max. Price ($)</lable>
<select name="maxprice">
<option value="100">100</option>
<option value="200">200</option>
<option value="300">300</option>
<option value="400">400</option>
.......
</select>
And this is the function that handle the inputs :
function filter_search() {
$max = $GET_['maxprice'];
$min = $GET_['minprice'];
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'price',
'value' => array( $min, $max ), //this is the line where i cant figure out how.
'compare' => 'BETWEEN'
)
)
);
$searched_posts = new WP_Query( $args);
return $searched_posts;
}
Am I correct to use the array for the value that I wish to compare?
This looks right, I have very similar code that works as expected:
The above gives me an array:
If we wanted to we could also add in our
meta_query
a type:But it seems to work as expected without the
meta_type
.If you’re using WooCommerce, do note that their metavalue is
_price
and notprice
.