Extend wp-admin search to use custom fields

UPDATE: For the WooCommerce-friendly version of this, see this article.

I think the title is self-explanatory but let’s detail the situation a bit:

Let’s presume you have a custom post type for Cars and for each car you have the VIN number in a custom field. You want to allow users to search from the admin directly by that field. Also, you need them to use the default search input:

Wp-admin search

The code

First we have to find the right hook to extend the search with. In our case I found the best results with the posts_search filter.

Next, the logic! Keep in mind this filter is being called in the get_posts function of the WP_Query class, so everywhere. That results in adding a check to see if we are on the right page.

Also, keep in mind that we are altering the “where” part of the actual SQL query.

Further usage

Like I mentioned before – this snippet checks if the search is performed in the admin, but that also means you can use it in the frontend. So if you’d like to extend the default WordPress search to enable custom field searches you can change the logic at the top. This can be easily switched to enable WooCommerce products search by SKU or similar.