How to exclude WordPress post types from the search!

Marc Wag­ner

June 21, 2022

2 min read|

Often you don’t need all Post Types in the search, or you want to pro­vi­de only a sel­ec­tion to your visi­tors. It can be quite hel­pful if you know how to imple­ment the who­le thing.

In the fol­lo­wing tuto­ri­al I will show you two ways to exclude Post Types from the search.

exclude_from_search #

This vari­ant is useful if you crea­te your own post types or if you want to exclude who­le post types from the search per­ma­nent­ly. To do this, add the “exclude_from_search” set­ting when you crea­te your post type.

'exclude_from_search' => true

It is just as easy to exclude post types from the search that were instan­tia­ted via an exter­nal plug­in. To do this, sim­ply add the fol­lo­wing snip­pet to your child the­me and replace “name_of_the_post_type” with the name of the post type.

/**
 * Exclude Post Type from Search
 */
add_action('init', 'excludePostTypeFromSearch', 99);

function excludePostTypeFromSearch(){
    global $wp_post_types;

    if(post_type_exists('name_of_the_post_type') && isset($wp_post_types['name_of_the_post_type'])){
        $wp_post_types['name_of_the_post_type']->exclude_from_search = true;
    }
}

Now all posts assi­gned to the Post Type will be remo­ved from the search results. You can repeat this for as many Post Types as you like.

pre_get_posts #

Alter­na­tively to the vari­ant from abo­ve, we can also mani­pu­la­te the Word­Press query direct­ly. This will only search for Post Types that we expli­cit­ly spe­ci­fy. For this pur­po­se we use the fol­lo­wing fil­ter:

  • pre_get_posts

The fol­lo­wing PHP snip­pet illus­tra­tes how to cus­to­mi­ze the search query:

 public function manipulate_search_query(WP_Query $query):WP_Query
 {
   if (!$query->is_search()) {
     return $query;
   }

   if (is_admin()) {
     return $query;
   }

   // Set the Post Types that should be searched for the keyword.
   $query->set('post_type', array('docs', 'page', 'post'));

   return $query;
 }

/*
 * Filter: pre_get_posts
 */
add_filter('pre_get_posts', 'manipulate_search_query', 10, 1);

Once you insert the script, only the posts & pages of post type “docs”, “page” and “post” will be sear­ched.

88e86fcb816eff22bc917094df2862d8dd5c0e978b333e6dd5f36f808990c261 96

Arti­kel von:

Marc Wag­ner

Hi Marc here. I’m the foun­der of Forge12 Inter­ac­ti­ve and have been pas­sio­na­te about buil­ding web­sites, online stores, appli­ca­ti­ons and SaaS solu­ti­ons for busi­nesses for over 20 years. Befo­re foun­ding the com­pa­ny, I alre­a­dy work­ed in publicly lis­ted com­pa­nies and acqui­red all kinds of know­ledge. Now I want to pass this know­ledge on to my cus­to­mers.

Hast du eine Fra­ge? Hin­ter­lass bit­te einen Kom­men­tar