Skip to content

Instantly share code, notes, and snippets.

@nickkuijpers
Created August 30, 2015 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickkuijpers/b845aa13459ff87d5e86 to your computer and use it in GitHub Desktop.
Save nickkuijpers/b845aa13459ff87d5e86 to your computer and use it in GitHub Desktop.
function custom_search_query( $query ) {
$custom_fields = array(
// put all the meta fields you want to search for here
"fw_options",
);
$searchterm = $query->query_vars['s'];
// we have to remove the "s" parameter from the query, because it will prevent the posts from being found
$query->query_vars['s'] = "";
if ($searchterm != "") {
$meta_query = array('relation' => 'OR');
foreach($custom_fields as $cf) {
array_push($meta_query, array(
'key' => $cf,
'value' => $searchterm,
'compare' => 'LIKE'
));
}
$query->set("meta_query", $meta_query);
};
}
add_filter( "pre_get_posts", "custom_search_query");
@MichaelChristman
Copy link

MichaelChristman commented Aug 22, 2017

Hey there nickkuijpers,

It may just be the way I tried to implement this but it seems that by doing
$query->query_vars['s'] = "";
you lose the ability to test against the post title and content in the search.
I was wondering if you could comment on a way to restore that functionality or if you think it would require a different approach to be used.

Cheers,
Michael

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment