Limit Search Form to Specific Post Types

If you’d like to limit the search form on WordPress site to specific post types globally, there’s and easy way to do that:

[gist id=”ca2f2dff2d6fde3bfd1e” file=”limit-search-to-post-types.php” lines=”2-9″]

But let’s say you want to have a specific search form search limited to one post type, but allow other search forms to search all post types?

Most tutorials I’ve run across suggest that you re-create all the search form markup and then add a hidden input to the form like this:

[gist id=”ca2f2dff2d6fde3bfd1e” file=”limit-search-to-post-types.php” lines=”12-13″]

You can then conditionally load that hidden field on the specific templates where where it is needed.

However, if you’re using get_search_form() and don’t want to completely replace all the search form markup, an alternative would be to do a string replace before outputting the form:

[gist id=”ca2f2dff2d6fde3bfd1e” file=”limit-search-to-post-types.php” lines=”15-22″]

For more reading on how this filter works, you can read the great inline docs in the WordPress codebase itself.

About Devin

I am a developer based in Austin, Texas. I run a little theme shop called DevPress and help manage a WooCommerce shop with Universal Yums. Find me on twitter @devinsays.

2 Responses

  1. I’m not a coder and I’m wondering if this php code would work in a widget. I want to have a limited search in “interviews” and I want the search tool to be in a widget on certain pages.

Leave a Reply