EN / ZH
Exclude Specific Posts, Pages, and Categories from WordPress Search Results, or Show Only Specific Categories

By default, the WordPress search mechanism returns results that include all pages, posts, and other content types on the site. While reorganizing Zhou Liang’s Blog recently, I needed to gain some control over what appears in search results and exclude content I don’t want readers to find.

From an efficiency standpoint, I’m not a fan of reinventing the wheel, so I searched for some existing code snippets. This post is purely a memo for myself.

Exclude Specific Posts or Pages by ID

//Exclude specific posts or pages by ID from search results
function Bing_search_filter_id($query) {
	if ( !$query->is_admin && $query->is_search) {
		$query->set('post__not_in', array(13,14));//IDs of posts/pages to exclude
	}
	return $query;
}
add_filter('pre_get_posts','Bing_search_filter_id');

Exclude All Posts Under Specific Categories

//Exclude all posts under specific categories from search results
function Bing_search_filter_category( $query) {
	if ( !$query->is_admin && $query->is_search) {
		$query->set('cat','-11,-13'); //Category IDs; prefix with minus sign to exclude; without the minus sign, search is limited to that category
	}
	return $query;
}
add_filter('pre_get_posts','Bing_search_filter_category');

Exclude All Pages from Search Results

//Exclude all pages from search results
function search_filter_page($query) {
	if ($query->is_search) {
		$query->set('post_type', 'post');
	}
	return $query;
}
add_filter('pre_get_posts','search_filter_page');