How To Exclude Pages From Search Results

Snippets, Tutorials | By | 10 January 2011 | Comments 3

One of my personal annoyances is the way WordPress search includes the blog pages within the search results, if your using thumbnails alongside your search results for example it makes the page look awful, the other downside is the page results are often irrelevant to what the reader is actually searching for.

But there is a way to remedy this issue and make a quick snippet addition so pages are never included within the search results.

This is a quick hack that takes place within the Theme Functions file (functions.php) file, so backup before you start tinkering!

functions.php

function no_pages_in_search($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
};
return $query;
};
add_filter('pre_get_posts', 'no_pages_in_search');

Now when you search on your blog you should have no pages show in the results, this snippet basically adds a filter on the results and removes any pages that match the search term.

Paul Maloney is a UK based web designer/developer and runs the design agency Tropica. He particularly enjoys using and working with WordPress and has a keen interest in typography. You can also follow Paul on Twitter.

Visit Paul Maloney's website

3 Comments

  • January 12, 2011
    • January 12, 2011
  • January 22, 2011

Leave A Comment.