Filter search results by post_tag if exist

Question

I want to get posts from search results using post_tag.
for example If a user input in the search form “party”. First, we search if “party” exists in post_tag and show all posts what have post_tag “party”. Else search default (mean search by post title contains the word “party”).

Here my code, I use pre_get_post

    function search_by_results_tags ($query){
    
     if ($query->is_search && !is_admin()) {
    
       $term = term_exists( $query->query_vars["s"], 'post_tag');
       if ($term !== 0 && $term !== null) {
            $taxquery = array(
                array(            
                   'taxonomy' => 'post_tag',
                   'field' => 'name',
                   //~ 'terms' => array($_REQUEST["s"]),
                   'terms' => array($query->query_vars["s"]),
                   'operator' => 'IN'
                   )
                );
            $query->set('tax_query', $taxquery);
            }
        $query->set( 'post_type', array( 'post', 'vacatures', 'agendas' ) );
        }
}

add_action( 'pre_get_posts', 'search_by_results_tags' );

My issue is, not get all posts.

Thank you

0
, , , , Baim Whello 3 years 2020-08-26T04:18:08-05:00 0 Answers 56 views 0

Leave an answer

Browse
Browse