How to use Meta Value Compare in WP_Query For Max and Min numbers

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?

1 Answer
1

This looks right, I have very similar code that works as expected:

function price_query_test() {

    update_post_meta( 7, '_price', 10 );
    update_post_meta( 12, '_price', 20 );
    update_post_meta( 18, '_price', 30 );
    update_post_meta( 72, '_price', 40 );

    $test = new WP_Query( array(
        'post_type'     => 'page',
        'meta_query'    => array( array(
            'key'       => '_price',
            'value'     => array( '10', '25' ),
            'compare'   => 'BETWEEN',
        ) ),
        'fields' => 'ids',
    ) );

    printf( '<pre>%s</pre>', print_r( $test->posts, 1 ) );
    die();

}
add_action( 'init', 'price_query_test' );

The above gives me an array:

Array
(
    [0] => 12
    [1] => 7
)

If we wanted to we could also add in our meta_query a type:

'meta_query'    => array( array(
    'key'       => '_price',
    'value'     => array( '10', '25' ),
    'compare'   => 'BETWEEN',
    'type'      => 'NUMERIC',
) )

But it seems to work as expected without the meta_type.

If you’re using WooCommerce, do note that their metavalue is _price and not price.

Leave a Comment