Search by type posts and taxonomy

I want that my search page give results of posts (that i want that show) and taxonomy

The code to get just two type of posts:

function searchfilter($query) {

      if ($query->is_search && !is_admin() ) {
          $query->set('post_type',array('lesson','series'));
      }
 return $query;
}

add_filter('pre_get_posts','searchfilter');

I want it to look for taxonomy too
Thanks

1 Answer
1

You can add a custom tax_query to your filter, and pass the search query to it:

function searchfilter($query) {

    if ($query->is_search && !is_admin() ) {
        $s = $query->get( 's' );
        $query->set('post_type', [ 'lesson', 'series' ] );
        $query->set( 
            'tax_query', 
            [
                [
                    'taxonomy' => 'your-taxonomy', 
                    'field'    => 'name', 
                    'terms'    => $s ,
                ] 
            ] 
        );
    }
    return $query;
}

add_action('pre_get_posts','searchfilter');

Leave a Comment