Free Wordpress Blog Setup

How to Exclude Pages from WordPress Search Results

By Editorial Staff in Tutorials
How to Exclude Pages from WordPress Search Results

By default, WordPress Search feature displays published posts and published pages in search results. Often when users are looking for something in a blog, it is most likely a post rather than a page. In this article, we will show you how to make your search more relevant and less crowded by excluding pages from WordPress search results.

First open your theme’s functions.php file and paste this code:

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

add_filter('pre_get_posts','SearchFilter');

Explanation: This code just searches for posts through setting the post_type. You can also make it do the opposite by setting the post_type to pages, so it only return pages in the search result.

Source: Bavotasan

What Next?

Digg it
Save This Page
Subscribe to WPBeginner
Stumble it
Free Wordpress Blog Setup

Comments

3 Responses to “How to Exclude Pages from WordPress Search Results”
  1. Rilwis says:

    This hack excludes not only pages from search results, but also other custom post types. So if we have many custom post types in our WP site, we can put them in the statement like this:

    $query->set(‘post_type’, array(‘post’, ‘custom-post-type’));

  2. Mohsen says:

    Hi
    may I put your tutorials in my blog with a link to wpbeginner.com? my blog is in Farsi and I think many persian users need these tips.
    thanks a lot

Share Your Opinions

Tell us what you're thinking...
and if you want a pic to show with your comment, then get gravatar!

Please make sure that you have read our Comment Policy.

Due to high volume of request from our readers, we are adding this feature that allows you to stay updated with this post's comments without having to participate in the discussion even though we would love your input as always. Don't worry we hate SPAM just as much as you do, so you will never receive any SPAM messages from our site and that's our promise to you.

Subscribe without commenting

Close Bar