Adding a custom field filter in a Relevanssi search takes a little bit of programming, because the filter needs to create a meta_query that Relevanssi understands.
Let’s assume we have some colour information in a custom field that’s called colour_field, and we want to use that to filter the search results. First, let’s add a dropdown in our search form:
<select name="colour"> <option value="any">Any colour</option> <option value="red">Red</option> <option value="green">Green</option> </select>
Then, we need to tell WordPress that we want to use a query variable called colour (the name here needs to match the name attribute of the select in the form):
add_filter( 'query_vars', 'rlv_add_qv' );
function rlv_add_qv( $qv ) {
$qv[] = 'colour';
return $qv;
}Then we need a function that reads in the query variable, formulates a meta_query and passes that to Relevanssi:
add_filter( 'relevanssi_modify_wp_query', 'rlv_add_meta_query' );
function rlv_add_meta_query( $query ) {
if ( isset( $query->query_vars['colour'] ) && ! empty( $query->query_vars['colour'] ) ) {
$meta_query = array(
array(
'key' => 'colour_field',
'value' => $query->query_vars['colour'],
'compare' => '=',
),
);
$query->set( 'meta_query', $meta_query );
}
return $query;
}If you need to have multiple meta fields in the same search, you must add them to the same meta_query – you can only have one. WP_Query documentation has a good example of what that looks like, so take a look at that if you need multiple custom fields.