Support

Account

Home Forums General Issues Querying values by the URL

Solving

Querying values by the URL

  • Is it possible at all to filter posts that have a certain value by URL?

    Example:

    example.com/events/date_picker?=07082013

    This would bring up all posts that have the value of 07082013 in the field called date_picker?

    I know you have this for relationship fields, but what about the others?

    Thanks for any help.

  • You’re looking at doing some custom wp_query filtering! Check out the Custom Field Parameters, this will give you a rundown on how to implement.

    I don’t have quite enough time to look into pulling in GET parameters, but here’s a sample of custom field filtering that I have open in front of me. The first one does actually look at the URL for variables, but probably not the proper WP way.

    Use an action hook, make sure that you have your URL variable and the right post type, then apply your field filters:

    
    add_action('pre_get_posts', 'wpse71814_filter_search');
    function wpse71814_filter_search( $query ){
    
         if( isset($_REQUEST['search']) && ($query->query_vars['post_type'] == 'properties') ){
    
             //Collect user input from $_GET for example
            // Protect yourself!
            foreach($_REQUEST as &$get){ $get = mysql_real_escape_string($get); }
            $meta_query = $query->get('meta_query');
    
            $meta_query[] = array(
                'key'       => 'price',
                'value'     => array($_REQUEST['price_min'], $_REQUEST['price_max']),
                'type'      => 'NUMERIC',
                'compare'   => 'BETWEEN'
            );
    
            if($_REQUEST['location'] != 'any'){
                $meta_query[] = array(
                    'key'       => 'district-rel',
                    'value'     => serialize(array(0=>$_REQUEST['location'])),
                    'compare'   => 'LIKE'
                );
            }
            $query->set('meta_query',$meta_query);
    
        } // if isset
    
        return $query;
    }
    

    For this example, I’m filtering post type “properties” and doing 2 meta queries: firstly inside a price range (price_min and price_max), and secondly if a location variable has been provided I am filtering on a district_rel custom post relation field.

    Let me know if you want a hand adapting this for your date field 😉

  • Oh, and it might be a good idea to orderby => meta_value_num if you’re using integer values like in a Unix timestamp.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Querying values by the URL’ is closed to new replies.