While working on a potential new plugin idea I tried to find the most future-proof and inclusive method to remove a built-in post type from the search results. In my case, I am actually trying to remove posts from the search results, but that lead me to an often Google-d method to exclude pages from search results.
The common solution is to set the query variable to ‘post’, however this limits the search results specifically to posts and nothing else. By default WordPress searches posts, pages and attachments. However, there are plenty of other plugins that create post types that you might want to have searchable (eCommerce ‘product’ post types, for instance).
This little snippet allows you to selectively exclude post types from search results (like pages, in this example), without monkeying around with any others. It’s great because you can set it and forget it – install and create other post types without worry that they will suddenly not show up on your search results*.
*It should be noted that if you are creating a custom post type and you don’t want to have it in the search results, don’t use this method. Just set the exclude_from_search
to true when you register the post type.
Leave a Reply