# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Search](https://wpide.com/library/category/search/)
- Tags: search, custom-fields, meta
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/search-custom-fields/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Search Inside Custom Fields" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
