wp query – Using ‘meta_query’ with the ‘pre_get_posts()’ hook disables searching for post titles

Question

I tried using only the pre_get_posts() hook to add some custom fields to the default posts search. But it didn’t work. With the code below, excepting the last code line, neither titles, nor content, nor custom fields can be searched.

After coming across @gmazzap’s answer, I completed the code as you can see below. That made the custom fields searchable, but not the post titles and content. My question is: Is there anything else that can be done just in pre_get_posts() so that searching for titles and content can also be restored?

add_action( 'pre_get_posts', function( $query ) {
    if( is_admin() || ! $query->is_search 
        || ! $query->is_main_query() ) { return; }

    $meta_query = 
        array( 
            'relation' => 'OR', 
            array(
                'key' => 'extra',
                'value' => get_search_query(),
                'compare' => 'LIKE'
            ), 
            array(
                'key' => 'lang_ro',
                'value' => get_search_query(),
                'compare' => 'LIKE'
            )
        );

    $query->set( 'meta_query', $meta_query );

    $query->set( 'orderby', array( 'title' => 'ASC' ) );

    // this activated the custom fields searching; unseting 
    // `$query->query_vars['s']` and setting`$query->is_search` 
    // to false not changed something - taken from @gmazzap
    $query->set( 's', '' );
} );

0
Iurie 1 month 2022-10-17T14:43:32-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse