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. it seems that it is searching through the revisions, finding old content. any idea how to limit the content to current content only???

  2. Just came here to say: DUDE!

    Awesome. Exactly what I was looking for.

    Thank you.

  3. Vivek Shingala Avatar
    Vivek Shingala

    It works but it doesn’t return all products in the search result. Please suggest

  4. This kinda worked for me. It works if my urls is just ?s=search_query. But if I do something like ?s=search_query&post_type=webinars it breaks. It doesn’t find anything.

    I’m wondering if this has to do with the new esc_sql change? Maybe this needs an updated version?

  5. Thanks! This works for me. However, can you help me with my problem? My problem is, for example: example.com/?s=customfield1,customfield2 it is okay I got result. But if I search with more than 2 custom field like for example.com/?s=customfield1,customfield2,customfield3 I got no result. Sorry about my English and TIA!

  6. That is what I was looking for! I saved a lot of time! great thanks!

  7. In general, I don’t leave comments, but this is snippet of code blew me away. I’ve spent days trying to figure out how to do this, with and without plugins. Yours is such an elegant solution that I have to say THANK YOU!!

  8. That’s brilliant! Thank you so much!

    One question: How to restrict to the entire keyword? Like, if I am searching “Rose”, I would like to not include “Rosemary”. Make sense?

    Any guidance on this issue, would be great.

    Thank you!

  9. Hristo Eftimov Avatar
    Hristo Eftimov

    Awesome! It works perfectly 🙂

  10. Thanks a lot. This code fixed the problem~

  11. Damian Avatar
    Damian

    Hi! Is this should works with ACF Pro 5.6.x and WordPress 4.9.5?

  12. Baptiste Avatar
    Baptiste

    Same. I’m just a big smile now. Thanks a ton!

  13. James P Avatar
    James P

    All these people having success getting this code to work. I’m just sitting here with SQL errors caused by duplicate LEFT JOINS for the postmeta table ¯\_(ツ)_/¯

  14. Sanchit Gupta Avatar
    Sanchit Gupta

    Thanks, it works Perfectly with ACF.

  15. You are an absolute legend! Thanks a lot. Ping me your PayPal I’ll shout you a beer 😉

  16. Thank You!!

    It works perfectly, I just pasted the code to function.php.

    Have a great day!

  17. Hi – this is super helpful! However, it doesn’t work if you are trying to Load More results via AJAX – any thoughts on how to search all the meta fields when using AJAX?

  18. Daniel Friberg Avatar
    Daniel Friberg

    Thanks for this snippet Adam.
    I got one issue though. When I search for a meta value my pagination doesn’t work, I get a 404 on pages above page 1. The results are perfectly fine on the first page.

    If I search for a string that exists in both the posts- and postmeta-table my pagination indicates 6 pages (for example) on the first search-results-page. When navigating to page 2 the pagination indicates 2 pages, so it seems that the meta value isn’t included in the paginated results on other pages than the 1st.

    Do you know of any solution for this problem?

  19. brilliant, work perfectly!!

  20. Thanks a lot mate, works like a charm!

    One thing I’d like to share, when I try to filter WooCommerce products at the back-end, based on a custom field, every time the URL contains “?s” (which means it’s a search query), the result is always empty. So I had to put a
    ( ! is_admin() )
    check at your codes, to make sure this only happens at the front-end. I only needed this at the front-end anyway, so no problem for me.

    Cheers.

    1. Ditte Risgaard Avatar
      Ditte Risgaard

      Where do you add that to the code?

  21. Very useful, thank you very much !!

  22. Raja Bhaiya Avatar
    Raja Bhaiya

    Its working and so much……:D

  23. Hi Adam.

    I used your code and it was working great, but it is not working from wp version4.9.x and the latest 5.0.3.

    Any chance you can update this code, please?

    Many thanks.

    1. Mine is not working also WordPress 5.2.1
      Any luck on this??

    2. Benjamin Arandjelovic-Vaughan Avatar
      Benjamin Arandjelovic-Vaughan

      Love this chunk of code and very useful. Thanks for sharing

      Just a heads up for anyone reading this WP V 4.9+ . Found that it works if you uniquely identify your call to postmeta by giving it an alias. e.g. cfmeta below

      …LEFT JOIN ‘.$wpdb->postmeta. ‘ cfmeta ON ‘. $wp->…

      then in the next query

      …OR (cfmeta.meta_value LIKE $1)”…

      Hope that helps anyone in the future and thanks again for the awesome code chunk!

  24. Thank you for this tutorial and code snippet! I tried it today with WordPress 5.1.1 and it worked beautifully. For those interested on following up some of the comments above: I personally did not experience any problems with pagination and did not have to modify any part of the code. My theme is one made from scratch, all custom fields were added without a plugin, and I am not using WooCommerce. This snippet went entirely into my functions.php file without any modifications and no issues arose.

    Much appreciated 🙂 Now I wonder what other precious offerings your website has to offer …

  25. Alexandra Avatar
    Alexandra

    Thank you very much!
    it realy works

Leave a Reply

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