Updated November 2026. I rewrote the code in this post and tested it on WordPress 7.1 and PHP 8.3. The version from 2015 broke for a lot of you, and the comments below explain exactly how. Thank you for those. The original code is at the bottom of the post if you need to compare.
Custom fields are one of the more powerful features in WordPress, and they’re most useful alongside custom post types. I use them all the time for product details like item numbers and prices. WordPress search doesn’t look at them, though. Search for a SKU and you get nothing, even when the product is sitting right there.
Here’s how to make the built-in search include custom fields, with one function and no plugin.
The Code
Add this to your child theme’s functions.php, or to a small plugin of your own. It works on the front-end search and on the search box in the admin list screens.
<?php
/**
* Extend WordPress search to include custom fields
*
* https://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/
*/
/**
* Which custom fields to search.
*
* Return an array of meta keys to search only those, for example
* array( 'sku', 'subtitle' ). Return an empty array to search every
* custom field except the hidden ones WordPress and plugins keep for
* themselves (keys that start with an underscore).
*/
function cf_search_keys() {
return array();
}
/**
* Should this query search custom fields?
*
* Yes for the main search query, on the front end and on the admin list
* screens. Any other query can opt in with 'cf_search' => true.
*/
function cf_search_applies( $query ) {
if ( $query->get( 'cf_search' ) ) {
return true;
}
return $query->is_main_query() && $query->is_search();
}
/**
* Add custom fields to the search part of the query
*
* https://developer.wordpress.org/reference/hooks/posts_search/
*/
function cf_search( $search, $query ) {
global $wpdb;
if ( '' === $search || ! cf_search_applies( $query ) ) {
return $search;
}
$keys = cf_search_keys();
if ( $keys ) {
$placeholders = implode( ', ', array_fill( 0, count( $keys ), '%s' ) );
$key_sql = $wpdb->prepare( "AND cf_meta.meta_key IN ( $placeholders )", $keys );
} else {
$key_sql = "AND cf_meta.meta_key NOT LIKE '\\\\_%'";
}
// For every "post_title LIKE 'term'" WordPress wrote, also accept a
// post that has a matching custom field. $1 is the term exactly as
// WordPress escaped it, quotes included.
return preg_replace(
"/\(\s*{$wpdb->posts}\.post_title\s+LIKE\s+('(?:[^'\\\\]|\\\\.)*')\s*\)/",
"({$wpdb->posts}.post_title LIKE $1) OR EXISTS ("
. " SELECT 1 FROM {$wpdb->postmeta} AS cf_meta"
. " WHERE cf_meta.post_id = {$wpdb->posts}.ID {$key_sql}"
. " AND cf_meta.meta_value LIKE $1 )",
$search
);
}
add_filter( 'posts_search', 'cf_search', 10, 2 );
That’s all of it. Search for a value that only exists in a custom field and the post now comes back.
How It Works
WordPress builds the search part of its query as a list of conditions: the title is like the term, or the excerpt is, or the content is. The posts_search filter hands you that piece of SQL before the query runs.
The function finds each title condition and adds one more alternative beside it: or the post has a custom field whose value is like the term. The check is an EXISTS subquery against the postmeta table, which is where custom field values live.
Because it reuses the search term exactly as WordPress wrote it, a search for two words still means both words have to match somewhere, the same as it does without this code.
Choosing Which Fields to Search
Out of the box it searches every custom field except the hidden ones. WordPress and most plugins store their own housekeeping in fields whose names start with an underscore, like _edit_lock and _thumbnail_id, and you don’t want a search for “12” matching an attachment ID.
To search only the fields you name, return them from cf_search_keys():
function cf_search_keys() {
return array( 'sku', 'subtitle' );
}
This is the answer to the question several of you asked about limiting the search to one field. It’s also the single best thing you can do for speed, which I’ll come back to.
One catch: Advanced Custom Fields stores each value under your field name, and a reference to the field under the same name with an underscore in front. The default setting skips the underscore copies, which is what you want.
Using It in Your Own Queries
The function only touches the main search query. Menus, widgets and any other queries that happen to run on a search results page are left alone. If you want it in a query of your own, ask for it:
$products = new WP_Query( array(
'post_type' => 'product',
's' => 'ZQX-1001',
'cf_search' => true,
) );
That also covers searches with extra parameters in the URL, such as a post type filter, since those still run through the main query.
What Was Wrong With the 2015 Version
The old code used three filters. It joined the postmeta table onto the query, rewrote the WHERE clause, and added DISTINCT to remove the duplicate rows the join created. It worked on a plain blog, and it failed in three ways that came up again and again in the comments.
“Not unique table/alias.” This was the big one. The join looked like this:
$join .= ' LEFT JOIN ' . $wpdb->postmeta . ' ON ' . $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
If anything else in the query had already joined postmeta, the database saw the same table name twice and refused. WooCommerce does that, and so does any query with a meta_query. PSJG and bert both worked out the fix in the comments, which is to give the joined table its own name. The new version uses a subquery with its own alias and never joins at all, so there’s nothing to collide with.
It ran on every query. The old code checked is_search(), which is true for every query on a search page and not only the search itself. That’s how it leaked into sidebars and menus. The new version checks the query it was actually given.
Search terms with an apostrophe. The pattern that found the title condition stopped at the first quote mark, so a search for a name like O’Brien was never extended to custom fields. The new pattern reads past escaped quotes.
Dropping the join also means there are no duplicates to remove, so the DISTINCT filter is gone.
Is It Safe?
Lukas asked whether this needs a prepared statement. It’s a fair question about any code that edits SQL by hand.
The search term is never inserted by this function. WordPress has already escaped it and placed it in the query, and the function copies that finished, quoted value from one part of the SQL to another. The only thing it adds from outside is your list of field names, and those go through $wpdb->prepare().
Speed on Large Sites
Tim Wakeling ran the old version on a WooCommerce store with a few thousand products and watched search slow down. The rewrite fixes the errors, but it doesn’t remove the underlying cost, and you should know what that is.
A search like this asks the database to look inside every custom field value for the term. The meta_value column has no index that helps with that, so the work grows with the size of the postmeta table. On a blog with a few hundred posts you won’t notice. On a store with tens of thousands of products and dozens of fields each, you will.
Two things help. Name your fields in cf_search_keys(), because the meta_key column is indexed and narrowing by it cuts the work down sharply. And if search matters to your business at that scale, this snippet is the wrong tool. Use a search service built for it.
What It Doesn’t Do
- It doesn’t change what the results page shows. If you want to print the custom field that matched, that’s a change to your search results template.
- It doesn’t search WooCommerce variations. Those are separate posts attached to the product, and matching a variation’s SKU to its parent needs a different query.
- It doesn’t change the REST API search endpoint, which builds its results another way.
The last two came up often enough in the comments that I’ll write them up separately.
The Original 2015 Code
For reference, this is what the post used to recommend. Don’t use it on a new site.
Show the original code
<?php
/**
* Extend WordPress search to include custom fields
*
* https://adambalee.com
*/
/**
* Join posts and postmeta tables
*
* https://developer.wordpress.org/reference/hooks/posts_join/
*/
function cf_search_join( $join ) {
global $wpdb;
if ( is_search() ) {
$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
}
return $join;
}
add_filter('posts_join', 'cf_search_join' );
/**
* Modify the search query with posts_where
*
* https://developer.wordpress.org/reference/hooks/posts_where/
*/
function cf_search_where( $where ) {
global $pagenow, $wpdb;
if ( is_search() ) {
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
/**
* Prevent duplicates
*
* https://developer.wordpress.org/reference/hooks/posts_distinct/
*/
function cf_search_distinct( $where ) {
global $wpdb;
if ( is_search() ) {
return "DISTINCT";
}
return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );