Query Posts by Custom Field ‘Price’

Use the pre_get_posts action to detect some filter vars in the URL and filter the query accordingly.

For example, say your form sets price_low and price_high GET vars, so the URL looks like:

domain.com/?price_low=100&price_high=1000

Then your filter function checks for the presence of those vars and creates the meta_query. This example is checking if it’s the main query on the home page, see the Conditional Tags page for how to check if other types of queries are happening, like a category or tag, etc..

function wpa_filter_home_query( $query ){
    if( $query->is_home()
    && $query->is_main_query()
    && isset( $_GET['price_low'] )
    && isset( $_GET['price_high'] ) ) {
        $meta_query = array(
            array(
                'key' => 'price',
                'value' => array( $_GET['price_low'], $_GET['price_high'] ),
                'type' => 'numeric',
                'compare' => 'BETWEEN'
            )
        );
        $query->set( 'meta_query', $meta_query );
    }
}
add_action( 'pre_get_posts', 'wpa_filter_home_query' );

EDIT- example of a simple form to submit values. Omitting the action attribute will submit the form to the current page.

<form method="GET">
    <input type="text" name="price_low">
    <input type="text" name="price_high">
    <input type="submit">
</form>

Leave a Comment