Search WordPress by Custom Fields without a Plugin

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
<?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():

PHP
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:

PHP
$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:

PHP
$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
<?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' );
Filed under:
Share

94 responses

  1. Not working

  2. Simple and awsome!!!!!!!

  3. what is $1 in there? and its working for me 🙁

  4. This code seems to work perfectly. Have you looked into modifying the WordPress Rest API search results endpoint so it does the same left join on postmeta, is that possible or would it require a custom endpoint? I want to do a search programmatically that includes postmeta ideally via the API.

  5. Great, works like a charm.

    How can I modify this code to search only 1 custom field?

    Thanks,
    Dean

  6. Works great. Thanks

  7. This worked great, thank you! I was just wondering, is it possible to output the text where the term was found? By default WordPress will just show an excerpt of the page/post and that doesn’t seem very relevant to the search being performed.

  8. Hello there! This is a very helpfull piece of code!
    Does anybody has any ideea how to make it to search inside group sub_fields?

    Thanks in advance for the help!

  9. This is great, but for completeness for the newbie, could supply a usage example at the end so the aforementioned newbie doesn’t have to trawl the web searching for an example on how to put it into practice?

  10. code is still working great with wp 6.3.1

  11. Thank you.

    But I have an additional question

    Is there a way to include only the values from the ACF in the WordPress search results?

    I don’t want to include the field labels, just the value in the search.

  12. Richard Eassom Avatar
    Richard Eassom

    This is perfect, thank you! I added some data in an ACF repeater and now it’s searching that data.

Leave a Reply

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