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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.