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. Hello,
    Are you sure is it safe?
    Don’t you need to use prepared statement or any escaping?

  2. Hi Adam,
    This is also not working for me. I’m getting a dump of sql code:

    WordPress database error: [Not unique table/alias: ‘eh9aal_postmeta’]
    SELECT SQL_CALC_FOUND_ROWS DISTINCT eh9aal_posts.ID FROM eh9aal_posts INNER JOIN eh9aal_postmeta ON ( eh9aal_posts.ID = eh9aal_postmeta.post_id ) INNER JOIN eh9aal_postmeta AS mt1 ON ( eh9aal_posts.ID = mt1.post_id ) LEFT JOIN eh9aal_postmeta ON eh9aal_posts.ID = eh9aal_postmeta.post_id WHERE 1=1 AND (((eh9aal_posts.post_title LIKE ‘%my%’) OR (eh9aal_postmeta.meta_value LIKE ‘%my%’) OR (eh9aal_posts.post_excerpt LIKE ‘%my%’) OR (eh9aal_posts.post_content LIKE ‘%my%’)) AND ((eh9aal_posts.post_title LIKE ‘%search%’) OR (eh9aal_postmeta.meta_value LIKE ‘%search%’) OR (eh9aal_posts.post_excerpt LIKE ‘%search%’) OR (eh9aal_posts.post_content LIKE ‘%search%’))) AND ( eh9aal_postmeta.meta_key = ‘dates_0_date’ AND ( ( ( mt1.meta_key LIKE ‘dates_%_date’ AND mt1.meta_value >= ‘20190905’ ) ) ) ) AND eh9aal_posts.post_type = ‘vso_event’ AND ((eh9aal_posts.post_status = ‘publish’)) GROUP BY eh9aal_posts.ID ORDER BY CASE WHEN eh9aal_posts.post_type = ‘page’ THEN ‘1’ WHEN eh9aal_posts.post_type = ‘vso_event’ THEN ‘2’ WHEN eh9aal_posts.post_type = ‘post’ THEN ‘3’ WHEN eh9aal_posts.post_type = ‘vso_venue’ THEN ‘4’ WHEN eh9aal_posts.post_type = ‘vso_artist’ THEN ‘4’ ELSE eh9aal_posts.post_type END ASC, eh9aal_posts.post_title ASC LIMIT 0, 12

  3. Hi Adam! How i can display the content of the custom field in search results?
    For example, i have custom field ‘car_description’
    And text in it: yellow car with red line
    My search query: yellow car
    I got the page with this metabox in search results, but displaing only contents of the field ‘the_content’

  4. It seems to be not working with multiple custom fields (meta_query) … ?

  5. hi man,

    you saved me hours of research. BIg thanks from France!

  6. Tim Wakeling Avatar
    Tim Wakeling

    This code works beautifully but I’ve found that on our WooCommerce site with a few thousand products each with a lot of attributes, the addition of the DISTINCT keyword (the third step here) makes the query take over 5 seconds, compared with 0.1 seconds without it.

    Any thoughts as to how to get round this? I’m trying to come up with a solution myself too!

  7. Ufuk Cergenç Avatar
    Ufuk Cergenç

    Thx a lot, simple useful code.

  8. Many thanks for your article.
    Work like a charm!
    Using WP 5.3.2 and ACF Pro 5.8.7

  9. Too quick…
    I also changed the preg_replace with

    if ( is_search() ) {
    $where = preg_replace(
    “/\(\s*wp_posts.post_title\s+LIKE\s*(\'[^\’]+\’)\s*\)/”,
    “(wp_posts.post_title LIKE $1) OR (wp_postmeta.meta_value LIKE $1)”, $where );
    }

  10. Thanks.

    But I think it’s better to give a unique name for LEFT JOIN table.

    $join .=’ LEFT JOIN ‘.$wpdb->postmeta. ‘ !!!NAME!!! ON ‘. $wpdb->posts . ‘.ID = !!!NAME!!!.post_id ‘;

    $where = preg_replace(
    “/\(\s*”.$wpdb->posts.”.post_title\s+LIKE\s*(\'[^\’]+\’)\s*\)/”,
    “(“.$wpdb->posts.”.post_title LIKE $1) OR (!!!NAME!!!.meta_value LIKE $1)”, $where );

    Otherwise there may be a conflict caused by multiple wp_postmeta joins.

  11. Thank you so much !

  12. Daniel Crabbe Avatar
    Daniel Crabbe

    This looks good but can’t see how you define what custom fields to search through? We will have hundreds on our current project and I’m guessing that this searches all act fields somehow? Which would be a bit heavy as content builds up.

  13. Nice… it’s working for me.
    But, how make search include table terms.

    i mean table wp_postmeta include wp_terms.

    Thanks

  14. Great work! How is it possible to use this for search results in custom loops?

    e.g.:

    $args = array( s => $keyword, ‘post_type’ => ‘custom’ );

    $loop = new WP_Query($args);
    if ($loop->have_posts()) {
    while ($loop->have_posts()) {

    $loop->the_post();
    get_template_part(‘public/template/results’);
    }
    } wp_reset_postdata();

  15. Thank you.

  16. Hi, thank you for this. A lot (almost all) of my content is in the custom field.
    Is there a way to make it works with filtering? As in ?s=search_keyword&post_type=cpt_slug

  17. Belarmino Nicolau Avatar
    Belarmino Nicolau

    Hi guys,

    I’m newbie on wordpress developing. So how to implement this code or how to call it?

    best regards.

  18. Thanks

  19. Hi Adam,
    Thanks a lot for sharing this, it’s been so useful to me !
    Cheers from France

  20. Husain Shaikh Avatar
    Husain Shaikh

    Hi ,
    Thanks you So much. it works perfect.

  21. Thanks Adam, worked like a charm.

  22. Goldy Live Avatar
    Goldy Live

    I just tried this on the latest WP version (5.7) in combination with Advanced Custom Fields PRO Version 5.9.5 and it works fine so far! I’m still a bit cautious though as this is quite an old topic and I don’t see any recent replies, however, I also didn’t find a more recently confirmed solution elsewhere other than using plugins, but I don’t want to use a plugin for just this purpose.

    The code seems fine as far as I can tell, and I’m pretty confident that it’s not a security risk of any kind but I don’t know the WP search system well enough to be able to tell if it might not lead to unexpected search results in some cases. So far I haven’t seen anything like that though:)

    Would be great to see more recent confirmations or thoughts from other people here as well.

  23. Christian Avatar
    Christian

    It works perfectly! Tested on WP 5.7.1 and WooCommerce 5.1.0. Thank you!!

  24. Alex Bajic Avatar
    Alex Bajic

    Still works, thank you so much…

  25. Carlos Faria Avatar
    Carlos Faria

    Had to change these two lines to get it working on WP 5.8.1 as I had an error ( Not unique table/alias: ‘wp_postmeta’ )

    $join .=’ LEFT JOIN ‘.$wpdb->postmeta. ‘ ON ‘. $wpdb->posts . ‘.ID = ‘ . $wpdb->postmeta . ‘.post_id ‘;

    to

    $join .=’ LEFT JOIN ‘. $wpdb->postmeta . ‘ AS post_metas ON ‘ . $wpdb->posts . ‘.ID = post_metas.post_id ‘;

    and

    “(“.$wpdb->posts.”.post_title LIKE $1) OR (“.$wpdb->postmeta.”.meta_value LIKE $1)”, $where );

    to

    “(“.$wpdb->posts.”.post_title LIKE $1) OR (post_metas.meta_value LIKE $1)”, $where );

    Hope to help someone ;D

    1. Greatest man alive!

    2. Thanks a lot !
      Work like a charme

Leave a Reply

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