Excluding Post Types and Pages from Search Results

Version audio de cet article
Excluding Posts Types and Pages from your search filter is actually pretty easy especially when your website is a blog with a post type you don’t want to be displayed in your search results.
In order to do so, we’ll need the pre_get_posts filter. Here’s the function we’ll need to inject into our functions.php file·
Excluding Post Types and Pages from Search Results
function ViaSearchFilter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts','ViaSearchFilter');We’re making sure that the pre_get_posts filter runs only with the $query variable only specifiying the Search Query within the condition.
At a later time, we’ll take a look at other ways to exclude the Posts Types from the Search.