I recently had to extend the search to include custom fields in WordPress admin. I created a custom post type called “document” and a few custom fields such as “_file_name” and “_url”. Unfortunately, it’s not possible to search by custom field value in WordPress admin, so I had to hook into the native WordPress search and tweak it.
In order to change the search query, you need to hook into pre_get_posts action. The pre_get_posts action gives developers access to the $query object by reference (Read more at WordPress Codex).
Here’s the code. You can change $post_type and $custom_fields according your needs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
function extend_admin_search( $query ) { // Extend search for document post type $post_type = 'document'; // Custom fields to search for $custom_fields = array( "_file_name", ); if( ! is_admin() ) return; if ( $query->query['post_type'] != $post_type ) return; $search_term = $query->query_vars['s']; // Set to empty, otherwise it won't find anything $query->query_vars['s'] = ''; if ( $search_term != '' ) { $meta_query = array( 'relation' => 'OR' ); foreach( $custom_fields as $custom_field ) { array_push( $meta_query, array( 'key' => $custom_field, 'value' => $search_term, 'compare' => 'LIKE' )); } $query->set( 'meta_query', $meta_query ); }; } add_action( 'pre_get_posts', 'extend_admin_search' ); |
This code seems to be limiting the admin search to ONLY that particular custom field key.
Yes it seems to omit search by title or other fields.
Is there a way to include existing search but ALSO look for custom fields and not JUST custom fields.
Thanks.
Thanks for your code. Here’s how I added the feature to search BOTH title and meta.
Taken from here:
https://wordpress.stackexchange.com/questions/78649/using-meta-query-meta-query-with-a-search-query-s/208939#208939
Basically I just added the $query->set(‘_meta_or_title’, $search_term);
and gave the actions priorities (sql has to be after).
Great piece of code did just what I wanted. I added all my custom fields and now they are all searchable.
$custom_fields = array(
“grave_number”,
“age_at_death”,
“date_of_death”,
“date_of_burial”,
);
But now I can’t search by Title or Name so really we haven’t extended the search facility……how can we get both to work and it will be perfect?
Thank you.