Steps
-
Add the PHP code to your theme’s
functions.phpfile or a PHP snippets plugin. -
Replace
5, 8, 12with your actual WordPress category IDs. -
Save and activate the snippet.
-
Search your website to verify the excluded categories no longer appear.
/**
* Exclude selected categories from search results
*/
function custom_exclude_categories_from_search( $query ) {
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$excluded_categories = array( 5, 8, 12 );
$query->set( 'category__not_in', $excluded_categories );
}
}
add_action( 'pre_get_posts', 'custom_exclude_categories_from_search' );
Tested on
WordPress 6.8
Reported by the author on November 16, 2026. WPFolks has not verified this.
Not tested against WordPress 7.1.5. It may still work.
