How to extend search for custom post types in WordPress admin

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.

WordPress admin search

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).

WordPress admin search

Here’s the code. You can change $post_type and $custom_fields according your needs.

One thought on “How to extend search for custom post types in WordPress admin”

Leave a Reply

Your email address will not be published. Required fields are marked *