Development & EngineeringJun 21, 2022
How to Exclude WordPress Post Types from Search!
Often, you don't need all post types in the search, or you want to provide your visitors with only a selection. It can be quite helpful to know how to implement this.
In the following guide, I will show you two ways to exclude post types from the search.
exclude_from_search
This method is helpful if you create your own post types or want to permanently exclude entire post types from the search. To do this, you add the setting "exclude_from_search" when creating your post type.
'exclude_from_search' => true
Post types instantiated via an external plugin can also be easily excluded from the search. For this, simply place the following snippet in 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, we can also manipulate the WordPress query directly. This way, only post types that we explicitly specify will be searched. We use the following filter for this:
- pre_get_posts
The following PHP snippet illustrates how to adjust 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 the post types "docs", "page", and "post" will be searched.