Search WordPress by custom fields without a plugin
Anyone who has used ACF or plain custom fields knows how convenient they are. But did you know that the default WordPress search does not look into custom fields at all? Live and learn.
Problem: The WordPress search looks only at the title, excerpt and content in the posts table. Posts whose matching text is in a custom field are not found.
Solution: I will not reinvent the wheel and just publish the solution I found (see the source below): three filters that add the postmeta table to the search query.
Step 1. Join the postmeta table
All custom field values are stored in the postmeta table. To search them, join it to the posts table:
<?php
add_filter( 'posts_join', 'cf_search_join', 10, 2 );
function cf_search_join( $join, $query ) {
global $wpdb;
if ( $query->is_search() && $query->is_main_query() ) {
$join .= " LEFT JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id ";
}
return $join;
}
Step 2. Add the meta values to the WHERE clause
WordPress builds a condition like (posts.post_title LIKE '%term%') for every search word. We find it and add an OR on meta_value with the same value:
<?php
add_filter( 'posts_where', 'cf_search_where', 10, 2 );
function cf_search_where( $where, $query ) {
global $wpdb;
if ( $query->is_search() && $query->is_main_query() ) {
$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;
}
Step 3. Prevent duplicates
After the join, a post appears once for every meta row that matches, so add DISTINCT:
<?php
add_filter( 'posts_distinct', 'cf_search_distinct', 10, 2 );
function cf_search_distinct( $distinct, $query ) {
if ( $query->is_search() && $query->is_main_query() ) {
return 'DISTINCT';
}
return $distinct;
}
Put all three functions in functions.php. They change the search on the front end and in the admin post lists, so you can search the edit screens by custom fields too. The is_main_query() check keeps other queries on the search page (widgets, related posts) unchanged.
NOTE: This searches all meta values, including internal ones such as _wp_page_template or _edit_lock. On a big site the join also makes the search slower. If only a few fields matter, add a condition on meta_key to the join, for example AND {$wpdb->postmeta}.meta_key IN ('price', 'sku').
Sources: