NB: Make sure you do a back up of your theme, files and database before attempting the tutorials
Last modified : Sep 11 2022
Estimated reading time : 0 minutes, 52 seconds - 105 words
Share the post "Excluding Post Types and Pages from Search Results"
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.