WordPress Search Custom Meta Field Only

You are abusing pre_get_posts badly with that code. With pre_get_posts the point is to alter the main query. By doing that you reduce the number of necessary queries and save some processing time, plus keep the WordPress globals$wp_query, for example– neat for any other code that might need them. What you are doing is creating new globals and populating them with new queries. You are just hiding those new queries inside pre_get_posts.

If I understand what you are trying to accomplish, I believe you need this:

function search_meta_only_wpse_198762($qry) {
  if ($qry->is_main_query() && $qry->is_search()) {
    $qry->set(
      'meta_query', 
      array(
        array(
          'key' => 'recipe',
          'value' => sanitize_text_field($query->query_vars['search']),
          'compare' => 'LIKE'
        )
      )
    );
    $qry->set('s',null);
  }
}
add_filter('pre_get_posts','search_meta_only_wpse_198762');

Leave a Comment