Limit Search to Post Type

Here's how to customize search forms to return results for specific post types. By using a filter you can choose exactly which search boxes are affected.

If you're using a lot of custom post types, your search results page could have content you don't want in it. One solution is to set 'exclude_from_search' => true when registering your post type ( more info ).

But what if you don't want to exclude them from all searches - just one specific search? I recently created a Videos section for a client site that pulls in content from the custom post type 'video'. We wanted a search box on that page that specifically searched through the video post type.

WordPress lets you specify a post type (or multiple post types) by using a hidden field in your search form.


You could use the get_search_form filter to rebuild the search form in that specific context, but here's a simpler approach:

[gist id=4b3e15a7166728a64a6231e4c70da135]

I know that the search form will include a submit button, so I'm sticking the hidden input in front of that by doing a find/replace.

No comments yet