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. Gerardo Avatar
    Gerardo

    It worked perfect, Thanks!

  2. Daniel Avatar
    Daniel

    It worked perfectly. Thank you, you’re the best! 🙂

  3. Webmasta Avatar
    Webmasta

    Works perfect with ACF (Advanced Custom Fields) 4.x and latest WordPress 4.2.2 here.

    Thanks a lot, you should publish this as a plugin at wordpress.org

  4. I echo the two previous comments. Your code worked perfectly.

  5. 2 days, two days, TWO DAYS!!!! of searching for a function that should be inside the wordpress core!!!!
    THANKS!!!!
    PS Is there a way to extend it to categories?
    Example: if there is a category “Cars” and the user types the word “car” in search field, it will return all posts inside category “Cars” (even if the word “car” is never mentioned in the post title or inside the content of the post).
    Thanks again for your precious help!

  6. Thanks it very helpful for Me…
    :-):-):-)

  7. Aaron Silver Avatar
    Aaron Silver

    Perfect, useful, well-done. Thank you!

  8. Hi man,

    I have been searching for this for days, and finally you got it! Even I posted twice in wordpress.org forums without any response. Great!!!

    Thank you so much!

  9. Thank you, great code! The only problem occurs when I try to to search two custom fields using the standard (?) AND operator. A single search per custom field works fine, but not for two search terms coming from two different custom fields.

  10. This is a great solution to a problem I had trying to search Custom Fields on my business directory. Like the other guys said, I’ve spent days trying to find something as simple as this without having to drill down into the core files and the fact that I can just add this to the functions.php is bloody marvelous.

    Thanks so much !!! 🙂

  11. Thanks!

  12. Robin Majumdar Avatar
    Robin Majumdar

    Brilliant, works like a charm.

    With your , as well as full credit and attribution , I’d like to translate your article in French on my tech blog?

    One note, readers should edit the functions.php file in their themes folder.

    Thanks again!

  13. Awesome. Just copy/pasted it into the functions.php and it worked. Thanks for the docu too 🙂

  14. This is great thanks. Was just wondering, is it possible to order the search results so that it lists posts from a specific post_type first? At the moment they’re in date order so would be fantastic if I could order them by the most relevant post_types?

  15. adam rowe Avatar
    adam rowe

    This is great! I’m using this in conjunction with updating a custom field with all of a post’s terms to allow WP’s search to find tags and categories.

  16. Thank you very very much. I am using the Advanced Custom Fields Plugin on a fairly large website and this just saved me an unknown amount of time (but it would have been alot).

  17. Worked perfectly with ACF – thank you!

    1. Hi Nikki,
      Could you take 1 minute and explain me what is the next step once the code is in functions.php ?
      I am using ACF as well with some fields but don’t get the point on how to implement that.

      Thank you

      Nicolas

      1. Hi Nicolas, did you solve that situation??

  18. Germano Bisson Avatar
    Germano Bisson

    Perfect, useful, well-done. Thank you!

  19. Thank you for this!

  20. Do you know why this would not work when filtering by price?

    I should jump back a bit and say a HUGE thank you! This is working great but with one small hangup.

    When your script is in the functions.php, it works, but as soon as you apply a WooCommerce “filter by price” it always returns with Zero results. As soon as you remove your script, the ability to filter by price does work.

    Do you have any idea why or what can be done to help keep your script in place but allow for product filtering?

  21. Awesome Solution! Thank you! Worked in one go!
    I am using it with WooCommerce to search on product’s meta field. Works brilliantly with Simple Products. But for Variable Products, it fails 🙁 !
    Any insights / thoughts / suggestions on how we can make it work for variable product search as well?

  22. David Keith Avatar
    David Keith

    This was extremely helpful. Thanks!

  23. BachMeister Avatar
    BachMeister

    I didn’t believe it still works, but it does! Thank you so much!

  24. You Sir..have just saved me hours. Great bit of code and works perfectly. THANK YOU.

  25. Hello! First of all thank you very much for this article.
    I have a question: How do I extend this search to product variations?

    Waiting for help
    Thank you

Leave a Reply

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