Last updated on November 28, 2011. Tags: functions.php, WordPress search
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
Comment Rules and Reminders