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.
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.
I think the easiest way to get this working in a widget would be:
* Set up a basic search widget
* View your site and copy the html that the widget outputs
* Put that into a new HTML widget and add the hidden field to the markup
The PHP code really just outputs the markup you need. But you can do the same thing with just the markup itself.