Excluding a category (or categories) from the WordPress search results is easy peezy, however, that doesn’t stop most of the snippets I’ve found from doing it wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'pre_get_posts', 'ja_search_filter' ); | |
/** | |
* Exclude category 7 from search results. | |
* | |
* @since ?.?.? | |
* @author Jared Atchison | |
* @link https://gist.github.com/1300302 | |
* | |
* @param WP_Query $query Existing query object | |
* @return WP_Query Amended query object | |
*/ | |
function ja_search_filter( $query ) { | |
if ( $query->is_search && !is_admin() ) | |
$query->set( 'cat','-7' ); | |
return $query; | |
} |
This works great, thank you 🙂 How about if you want to exclude multiple categories?
$query->set( ‘cat’, ‘-1,-1347’ );
works perfectly. thank you so much
Hi Jared,
Very helpful post!
Is there a way to exclude certain pages too?
Yep, you should be able to use
post__not_in()
.http://codex.wordpress.org/Class_Reference/WP_Query
Sorry Jared, I didn’t see your reply before posting below!
Perfect, thanks for your help.
Found solution. If it’s helpful to anyone else the code is:
function SearchFilter($query) {
if ($query->is_search) {
$query->set(‘post_type’, ‘post’);
}
return $query;
}
add_filter(‘pre_get_posts’,’SearchFilter’);
Hello Admin… Please, where do i add this code in my blog?