A fresh mix of code snippets and tutorials

WordPress Exclude Custom Post Type from Search

Out of the box, WordPress search results include matches from any Custom Post Types that may be enabled via the theme template. For example, at htaccessbook.com, any matching content found in forum posts will be included in search results. This default behavior can be super convenient, but it is not always desirable. In this quick tutorial, you’ll see how to exclude Custom Post Types from WordPress search results.

Exclude Custom Post Types from Search Results

So let’s say that we have two Custom Post Types, “book” and “movie”. We want to exclude the movie post type from search results. To do so, we add the following code to our theme’s functions.php:

function shapeSpace_filter_search($query) {
	if (!$query->is_admin && $query->is_search) {
		$query->set('post_type', array('post', 'page', 'book'));
	return $query;
add_filter('pre_get_posts', 'shapeSpace_filter_search');

This code checks if the query is a search query and not an admin query. If so, it uses the set() method of WP_Query to set the value of the post_type parameter. Because we want to exclude the movie post type from the search query, we exclude it from the array. Notice:

$query->set('post_type', array('post', 'page', 'book'));

As you can see, here we specify that the post type used for search queries should be either post, page, or book. Thus the movie post type is excluded from the search results.

Of course, there are many ways to customize this snippet, to do things like allow other post types, exclude current post types, and even use other WP_Query parameters to modify other aspects of the search query. That’s the beauty of WordPress’ WP_Query class — it enables great control over virtually every aspect of the query.

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress