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:

// Change search function globally to search only post, page and portfolio post types
function prefix_limit_post_types_in_search( $query ) {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'post','page', 'portfolio' ) );
return $query;
add_filter( 'pre_get_posts', 'prefix_limit_post_types_in_search' );

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:

/* Hidden input field that can be added to search form */
<input type="hidden" name="post_type" value="portfolio">

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:

// Output a search for that only searches portfolio post types
$search = get_search_form( false );
$find = '</form>';
$replace = '<input type="hidden" name="post_type" value="portfolio">' . $find;
$search = str_replace( $find, $replace, $search );
echo $search;

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

Posted by:Devin

I'm a WordPress developer based in Austin, Texas. I run a little theme shop called DevPress and work for a startup called Nano. Find me on twitter @devinsays.

2 thoughts on “ Limit Search Form to Specific Post Types ”

  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.

    1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *