Can I exclude a specific category of a custom post type from both search and archives?

410 Views Asked by At

I have a custom post type "courses" and the taxonomy for categories within this post type is "course-category."

I have a course category called "Academy" and I would like to exclude that category from any search, and from any archive pages for that custom post type.

Right now I have this code snippet but it doesn't seem to be working. It's for the search exclusion only but I need to exclude the category in both search pages and archive pages.

function wpb_search_filter( $query ) {
    if ( $query->is_search && !is_admin() )
        $query->set('post_type', array('courses');
        $query->set( 'course-category','-68' );
    return $query;
}
add_filter( 'pre_get_posts', 'wpb_search_filter' );
1

There are 1 best solutions below

4
On BEST ANSWER

Have you tried using is_post_type_archive()?

function wpb_search_filter( $query ) {
    if ( $query->is_search && !is_admin() || $query->is_main_query() && !is_admin() && $query->is_post_type_archive('courses') ) {
        $query->set('post_type', array('courses');
        $query->set( 'course-category','-68' );
        return $query;  
    }
}
add_filter( 'pre_get_posts', 'wpb_search_filter' );