Exclude category from search results in WordPress

Issue

I am trying to exclude a specific category ID from showing in WordPress search results. I have tried with this code which I have found several places on the internet, but it does not seem to work. I have changed the ID to the correct ID.

function my_search_filter( $query ) {
if ( $query->is_search && !is_admin() )
$query->set( 'cat','-21' );
return $query;
}
add_filter( 'pre_get_posts', 'my_search_filter' );

Right now my solution is using the code below, where I have to manually insert every page ID. It is working, but not a good solution.

add_action('pre_get_posts','exclude_posts_from_search');
function exclude_posts_from_search( $query ){
    if( $query->is_main_query() && is_search() ){
        //Exclude posts by ID
        $post_ids = array(52384,52366,52058,52392,52374);
        $query->set('post__not_in', $post_ids);
    }
}

Would it be possible to use my current code with categories instead of every page ID? Or is the first code example the way to go, but with some changes?

Solution

Place the following function in your active theme functions.php file

function exclude_categories_from_search($query) {
    // run query only if we are searching
    if ( !$query->is_search )
        return $query;
    
    $term_ids = array( 19, 18, 214, 226, 20 ); add category/term ids 
    $taxquery = array(
        array(
            'taxonomy' => 'category', //Here add your taxonomy eg: category
            'field' => 'id',
            'terms' => $term_ids,
            'operator'=> 'NOT IN'
        )
    );

    $query->set( 'tax_query', $taxquery );

}
add_action( 'pre_get_posts', 'exclude_categories_from_search' );

Answered By – Martin Mirchev

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published