meta_query is overriding default search

Question

I’m using default search with get_search_form() function. I want to search also by custom fields, so I wrote a hook:

function search_products($query) {
        if (is_search() && $query->is_main_query() && !is_admin()) {
            $query->set('post_type', 'product');
            $my_custom_field = $query->query['s'];
    
            $meta_query = array(
                array(
                    'key'     => 'custom_field',
                    'value'   => $my_custom_field,
                    'compare' => 'LIKE',
                )
            );
            $query->set('meta_query', $meta_query);     
        }
    }
    
    add_action('pre_get_posts', 'search_products');

Problem is the search is not showing products filtered by title and also not showing products filtered by custom field. How to solve this?

0
osemec 4 months 0 Answers 13 views 0

Leave an answer