Excluding all Pages from Search Results

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.

function exclude_pages($query) {
   if ($query->is_search) {
      $query->set('post_type', 'post');
   return $query;

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.

Today In History



Leave a Reply

Note: Convet HTML, PHP, JavaScripts from HTMLify, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.