Halloween Sale 15% off Ends in See the plans
PHP

Search Inside Custom Fields

Lets the site search also match text stored in custom fields, such as a subtitle, location or product code, not just titles and content.

Don’t have WPIDE yet? Install it on your site

Code

// Custom field names to include in search (empty = all fields not starting with an underscore).
$wpide_search_meta_keys = array( 'subtitle', 'location' );

add_filter( 'posts_search', function ( $search, $query ) use ( $wpide_search_meta_keys ) {
    global $wpdb;

    if ( '' === $search || is_admin() || ! $query->is_main_query() || ! $query->is_search() ) {
        return $search;
    }

    $key_sql = $wpide_search_meta_keys
        ? "AND pm.meta_key IN ('" . implode( "','", array_map( 'esc_sql', $wpide_search_meta_keys ) ) . "')"
        : "AND pm.meta_key NOT LIKE '\\_%'";

    $pattern = '/\(' . preg_quote( $wpdb->posts, '/' ) . '\.post_content LIKE (\'(?:[^\'\\\\]|\\\\.)*\')\)/';

    $result = preg_replace_callback( $pattern, function ( $m ) use ( $wpdb, $key_sql ) {
        return $m[0] . " OR ({$wpdb->posts}.ID IN (SELECT pm.post_id FROM {$wpdb->postmeta} pm WHERE pm.meta_value LIKE {$m[1]} {$key_sql}))";
    }, $search );

    return null === $result ? $search : $result;
}, 10, 2 );

Notes

List the field names to search. Leave the list empty to search every visible custom field, which is slower on big sites.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.