I’d like to display all posts within a given price range. For example: When a user inputs 100 and 1000 (in two separate form fields) – my site will display all posts that have a custom field called price that has a numeric value between 100 and 1000.

Found this under the documentation for WP Query; however, I’m unsure as to how I create a query based on input from a form on my WordPress site.

$args = array(
'post_type' => 'product',
'meta_query' => array(
    array(
        'key' => 'color',
        'value' => 'blue',
        'compare' => 'NOT LIKE'
    ),
    array(
        'key' => 'price',
        'value' => array( 20, 100 ),
        'type' => 'numeric',
        'compare' => 'BETWEEN'
    )
)
);
$query = new WP_Query( $args );

Thank you for your time.

3 s
3

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 Reply

Your email address will not be published. Required fields are marked *