Excluding Pages and Posts from WordPress Search Results

E

Although I rarely use the search option on my site I noticed that my Contact page was being included in the search results. Not only did this seem pointless, it also looked strange slap-bang in the middle of the results page.

To exclude my Contact page from the search results I added this code block to my function library.

Dummy Content
// Exclude posts/pages from search results
function exclude_from_search($query) {
	if ($query->is_search) {
		$excluded = array(
			321,		// Sitemap
			523			// Contact Page
		);
		$query->set('post__not_in', $excluded);
	}
	return $query;
}

add_filter('pre_get_posts','exclude_from_search');

 

 

If you don’t currently use a function library you can read about setting one up here.

From the point of view of customising this function to meet your own needs, the important piece of code is the declaration of the $excluded array beginning on line 4. This array contains the IDs of the posts or pages you want to exclude.

An easy way to find post or page IDs is to select Posts or Pages from the WordPress Admin panel and place the mouse cursor over the appropriate post/page title. Your browser’s status bar should show a string similar to ../post.php?post=523&action=edit where the post/page ID is 523.

Note that the exclude_from_search() function is associated with the pre_get_posts hook using add_filter(). When this hook executes it passes the current query object – $query – to the exclude_from_search() function.

About the author

A native Brit exiled in Japan, Steve spends too much of his time struggling with the Japanese language, dreaming of fish & chips and writing the occasional blog post he hopes others will find helpful.

2 responses

2 Comments

Steve

Recent Comments

Recent Posts