{ Filter Search Results }

When implementing a number of custom post types, we may want to make sure some of them don’t appear in the site’s search results. A relatively easy way to handle this programmatically is via a filter, hooked into pre_get_posts.

We’re filtering the main $query here, so we want to be careful about where the filter is applied. Per $ignore, we’re making sure the current query isn’t in the admin or on a page that is displaying anything other than search results. Then we explicitly set which post types we want to include in the search. As the name of the filter hook suggests, we’re setting the query, or more specifically the query vars ($query->query_vars), before it retrieves any posts.

Note that this filter will now exclude all other post types, including those provided by other plugins. Many plugins register one or more of their own custom post types, which can end up in the search results if the”publicly_queryable” property in register_post() is not set to FALSE.