Skip to content

Instantly share code, notes, and snippets.

@aguilar1181
Last active June 13, 2019 15:36
Show Gist options
  • Save aguilar1181/c1dab7d614e96677b07d to your computer and use it in GitHub Desktop.
Save aguilar1181/c1dab7d614e96677b07d to your computer and use it in GitHub Desktop.
Admin search improvement to look in custom fields
<?php
//Improve admin custom search
function custom_search_query( $query ) {
$custom_fields = array(
// put all the meta fields you want to search for here
'meta_field',
);
$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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment