How To Search With Custom Meta Fields In WordPress

Trying to use your website’s search to include custom meta fields? All you may need is to add the code below into your WordPress theme’s functions.php file.

Searching By Meta Value

To search by custom meta values, you need to set your search query as per below in your WordPress theme’s functions.php file.

function custom_search_query( $query ) {
     if ( !is_admin() && $query->is_search ) {
          $query->set('meta_key', 'your_meta_key');
          $query->set('meta_value', 'your value');
          $query->set('meta_compare', '=');
     };
}
add_filter( 'pre_get_posts', 'custom_search_query' );

Using meta values in search & archives

To apply the same queries into your archives, replace the if statement line above to include $query->is_archive as per below.

if ( !is_admin() && $query->is_search || $query->is_archive ) {