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.
Thanks.
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
$query->parse_query($request);
$request['post_type'] = 'LAW';
// this is the actual manipulation; do whatever you need here
if(isset($_GET['search']))
$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';
$i++;
}
}
return($request);
}
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).