To achieve this custom feature we will use very interesting and effective trick. It will not affect default wp-admin search. We will just enrich it by adding special case.
In order not to affect default search let’s set a rule when we search by meta field.
In my case, i am setting such rule. I will use # prefix when i want to find a post by meta field.
For example,
if i type “inventory” and press enter, default WP-Admin search would work.
And if i type “#inventory” and press enter, it will look up into meta fields and show results by that data. Which is cool.
Now let me share small snippet which will bring this feature into your website wp-admin.
Search by specified custom field only
In this case our approach is clear: We reset default search term, and show the posts that contains meta keys that have values containing the given meta value.
add_action('pre_get_posts', function(){
if (!is_admin()) {
return $query;
}
if (!empty($_GET["s"]) and strpos(urldecode($_GET["s"]), "#") === 0) {
$query->set('s', "");
$query->set('meta_key', "META_KEY_NAME_HERE");
$query->set('meta_compare', "LIKE");
$query->set('meta_value', substr(urldecode($_GET["s"]),1));
}
}, 0);
Search by all custom fields
In this case we need different approach, because we need to cover all possible meta keys. So we will use database query for this case.
add_action('pre_get_posts', function(){
if (!is_admin()) {
return $query;
}
if (!empty($_GET["s"]) and strpos(urldecode($_GET["s"]), "#") === 0) {
global $wpdb;
$found_posts=$wpdb->get_col(
$wpdb->prepare(
"select post_id from $wpdb->postmeta where meta_value like %s",
substr(urldecode($_GET["s"]),1)
)
);
if(empty($found_posts))$found_posts=[0];
$query->set('s', "");
$query->set('post__in', $found_posts);
}
}, 0);
What we did here are:
- finding post ID-s which have corresponding meta data.(ignoring the names of meta keys)
- passing found post ID-s to wp-admin’s search results page.