On one of my post, I have shown how to exclude specific pages of your site from default WordPress search results. In this post we will share a snippet that would exclude all pages from your search results. This could be very useful for sites that doesn’t have any CPT (Custom Post Type). However, having CPT doesn’t mean that you can’t use this snippet. But you need to be extra careful. We will explain it within a minute but let’s take a look at the snippet first.
<?php
function exclude_pages($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts','exclude_pages');
?>
Now, just copy and paste this snippet on your theme’s functions.php file and update it. Yes, your are done. Feel free to try it out from your site’s search form.
For Custom Post Type Users
Above snippet works well in real life scenario. However, things might get little complicated if you are using Custom Post Type (CPT) on your website. Because CPT register function register_post_type uses an argument called “hierarchical”, the value of this argument needs to be set to “False”. Otherwise, WordPress will treat every single post of your CPT as a page and would get excluded because of the snippet we just mentioned.
Same rule applies for “Taxonomy”. While registering taxonomy for your CPT, make sure to set register_taxonomy function’s “hierarchical” argument has been set to false as well. Or posts under your registered taxonomy would get the same treatment.
Comment
Leave a Reply