Excluding Pages and Posts from WordPress Search Results

Steve September 9 Blogging with 2 and 0
Home/Blogging/Excluding Pages and Posts from WordPress Search Results

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.

// 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;



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 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


  • biosphera
    on September 18th, 2010 at 04:51

    Finally someone who has the solution. THX very much!

    • Author
      on September 18th, 2010 at 06:36

      You’re welcome biosphera.

Add comment

©Tech Otaku 2009 - 2016