I have a custom post type called LAW. LAW has three custom fields: LAW_DATE, LAW_TEXT and LAW_AUTHOR. I want to build a search page that allows me to search independently each of these custom fields. I.e. different criteria for each field, combined with and/or to each other.



1 Answer 1


The following function needs to be put in the functions.php of your template code. Or in a plugin.

function custom_search_query( $request ) {
    $query = new WP_Query();  // the query isn't run if we don't pass any query vars

    $request['post_type'] = 'LAW';

    // this is the actual manipulation; do whatever you need here
        $options = $_GET['search'];
    if (!empty($options)) {
        $i = 0;
        $request['meta_query'] = array(); // resetting any previously selected meta_queries that might "linger" and cause weird behaviour.
        // CAREFUL HERE ^ might not be desired behaviour

        foreach($options AS $key => $value) {
            $request['meta_query'][$i]['key'] = $key;
            $request['meta_query'][$i]['value'] = array($value);
            $request['meta_query'][$i]['compare'] = 'IN';
            $request['meta_query'][$i]['type'] = 'CHAR';

add_filter( 'request', 'custom_search_query' );

The above function assumes that the HTML form will be similar to this:

<input type="text|number" name="search[keyname1]" value="value1" />
<input type="text|number" name="search[keyname2]" value="value2" />

It makes no validation on the user input, (wordpress might do some of that but it's better if you do it).

  • This is really NOT the best example. Why you use request filter? Just for search. There are many other filter that will be better for search, no need to rewrite all requests. I would use posts_where_request action with checking of query is_search(). But it looks nice and clean, just IMO no need to use request.
    – Tommixoft
    May 21, 2012 at 13:47
  • Hi Mihai and thanks for the answer. I m sorry I m new to this. Where do you instruct to search in custom fields of a custom post type? All I see is you collect posted variables. Sorry for my ignorance, maybe you could point me to some online documentation.
    – p.a.
    May 21, 2012 at 14:15
  • @Tommix I use request filter because I typically use custom fields as sub-filtering which means I want it to be available on almost any page. If p.a. only needs this for the search behaviour he can use is_search() as you suggested. May 21, 2012 at 22:00
  • @Tommix about using posts_where_request if find it less, clean as you stated too. May 21, 2012 at 22:01
  • @p.a. I added a line of code to ensure that only posts of type LAW are returned. May 21, 2012 at 22:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.