How to exclude WordPress post types from the search!
Marc Wagner
June 21, 2022
Often you don’t need all Post Types in the search, or you want to provide only a selection to your visitors. It can be quite helpful if you know how to implement the whole thing.
In the following tutorial I will show you two ways to exclude Post Types from the search.
exclude_from_search #
This variant is useful if you create your own post types or if you want to exclude whole post types from the search permanently. To do this, add the “exclude_from_search” setting when you create your post type.
'exclude_from_search' => true
It is just as easy to exclude post types from the search that were instantiated via an external plugin. To do this, simply add the following snippet to your child theme 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 assigned to the Post Type will be removed from the search results. You can repeat this for as many Post Types as you like.
pre_get_posts #
Alternatively to the variant from above, we can also manipulate the WordPress query directly. This will only search for Post Types that we explicitly specify. For this purpose we use the following filter:
- pre_get_posts
The following PHP snippet illustrates how to customize 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 searched.
Artikel von:
Marc Wagner
Hi Marc here. I’m the founder of Forge12 Interactive and have been passionate about building websites, online stores, applications and SaaS solutions for businesses for over 20 years. Before founding the company, I already worked in publicly listed companies and acquired all kinds of knowledge. Now I want to pass this knowledge on to my customers.