Search result by range?

I have to search for posts that have in tags or custom fields a number(price): example 152. Each post have a price tag. How I do to search for all post greater than a price for example I need to search for all post who have a price tag of minimum 100.

Something like /?s=keyword&price>=300

Read More

Thx

Related posts

Leave a Reply

2 comments

  1. If you save the the price in a meta field, you can query posts using meta_query:

    <?php
        $the_posts = new WP_Query( array(
            'meta_key' => 'price',
            'orderby' => 'meta_value_num',
            'order' => 'ASC',
            'meta_query' => array(
                array(
                    'key' => 'price',
                    'value' => '100',
                    'type' => 'NUMERIC',
                    'compare' => '>='
                )
            )
        ));
    ?>
    <?php while ( $the_posts->have_posts() ) : $the_posts->the_post(); ?>
        <h1><?php the_title(); ?></h1>
    <?php endwhile; wp_reset_query(); ?>
    
  2. If the price is stored as a custom field you’ll need to use the meta_query argument of WP_Query (see Codex). For instance:

     //Get posts with custom field 'price' between 20 and 100
     $price_filtered = WP_Query(array(
         'meta_query'=>array(
             array(
                'key' => 'price',
                'value' => array( 20, 100 ),
                'type' => 'numeric',
                'compare' => 'BETWEEN'
             ),
          )
     ));
    

    (where price is the key of the custom field). Depending on how you might be implementing this (is it intended to be the ‘main query’ or not – you might want to use this at pre_get_posts)

    Edit

    If filtering a search result:

    add_action('pre_get_posts', 'wpse71814_filter_search');
    function wpse71814_filter_search( $query ){
         if( $query->is_search() && isset($_GET['min']) ){
    
             //Collect user input from $_GET for example
             $user_input_min_value = $_GET['min'];
    
             $meta_query = $query->get('meta_query');
    
             $meta_query[] = array(
                'key' => 'price',
                'value' => $user_input_min_value,
                'type' => 'NUMERIC',
                'compare' => '>='
             );
    
             $query->set('meta_query',$meta_query);
          }
    }
    

    Note: The original answer had a meta query which specified a range. The second answer has a meta query which filters for prices above some minimum value.

    Usage: /?s=keyword&min=300