Excluding static pages and some posts from WordPress search results

Last updated on November 28, 2011. Tags: ,

After reading my earlier post about preventing all static pages from appearing in WordPress search results, and the other one that's about doing the same to few selected posts, you might have thought of copying both codes in your functions.php file and modifying it to your specifications just to find out that it doesn't work.

You will notice however, that these two codes are exactly the same, except for one specific line (in bold).

For pages:

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

add_filter('pre_get_posts','SearchFilter');

For a specific category of posts:

function SearchFilter($query) {
if ($query->is_search) {
$query->set('cat','-10');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');

To filter out all static pages and a few posts from WordPress search results, you need to combine these two codes and not paste them as separate blocks in functions.php file. This is how you combine them.

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

After this, follow the instructions in Preventing certain posts from appearing in WordPress search results on how to assign posts in the "Hidden Post" category and how to remove this category from your category list.

Posted by Greten on September 21, 2009 under WordPress

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • StumbleUpon
  • Technorati

Related Posts

You might also be interested (randomly generated):

Post Comments





Comment Rules and Reminders

  • The links to the commentator's e-mail do not have nofollow tag. However, I will be very strict in approving comments.
  • When you comment, please say something that indicates that you indeed read my post. If your comment is a general statement that can fit to any blog post about any topic, it will be regarded as spam.
  • What you write in the name field may include keywords to your website provided that (1) it's only up to four words long and (2) at least one of these four words is your first name or nickname. I rather reply to Bob or to Joe Smith than to Online Marketing Tips.
  • Please double check your comment before clicking the "Post" button. Once you clicked it, there will be no way for you to edit your comment.
  • Fields marked with asterisks (*) are required. Your email will never be displayed in public.