I'm trying to interfere default WP search (?s=) to make it search through posts custom fields.

Firstly I'm trying to debug my search with this piece of code in functions.php:

function add_search_in_custom_fields( $query ) {
        'post_type', 'my_post_type',
        'meta_query', array(
                'key'     => 'my_key_title',
                'value'   => 'my_value_title',
                'compare' => 'LIKE'
    return $query;
add_action( 'pre_get_posts', 'add_search_in_custom_fields' );

What's strange - that I'm getting all posts (with my_post_type) - doesn't matter if there is value or not in posts custom field.

Seems like $query doesn't look at meta_query parameters at all.

Any ideas?

1 Answer 1


You are getting all post because you didn't pass meta query correctly. Try this below code

function add_search_in_custom_fields( $query ) {

  // check the query type.
  if ( $query->is_search ) {

    $meta_array = array(
        'key' => 'my_key_title',
        'value' => $query->query_vars['s'] ,
        'compare' => 'LIKE',

    // set meta query.
    $query->set('meta_query', $meta_array);
add_filter( 'pre_get_posts', 'add_search_in_custom_fields');

Hope this help !

  • Thanks for fixes Kumar. For those who want to search through all custom fields at once , i suggest Adam Balee solution (without plugins): adambalee.com/…
    – Sid
    Dec 9, 2016 at 12:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.