I'm using the following form html to generate a search function on a wordpress site:

<form method="get" action="<?php bloginfo('url'); ?>">
<input type="text" name="s" value="" placeholder="search&hellip;" maxlength="50" required="required" />
<button type="submit">Search</button>

It works ok, but I wish to only return results for a specific custom post type. I'm using the search.php template from twentysixteen theme which contains this:

<?php  global $wp_query; ?>
<h1 class="search-title"><?php echo $wp_query->found_posts; ?> Results found for: <span><?php the_search_query(); ?></span></h1>

         <?php if ( have_posts() ) { ?>
           <ul class="results">
             <?php while ( have_posts() ) { the_post(); ?>
                  <?php if ( has_post_thumbnail() ) { ?><div class="post-image"><a href="<?php echo get_permalink(); ?>"><?php the_post_thumbnail('thumbnail');?></a></div><?php }?>
                                    <div class="post-content">
                                    <h3><a href="<?php echo get_permalink(); ?>"><?php the_title();  ?></a></h3>
                  <p><?php echo substr(get_the_excerpt(), 0,140); ?>... <a href="<?php the_permalink(); ?>">Read More</a></p>
             <?php } ?>
         <?php } ?>

Is there a variable that I can add somewhere to only return results for a specific post type? Thanks

2 Answers 2


Ok, so I did a little more digging around and it turns out to be pretty easy. I just needed to add a hidden input into the search form. Posting this here for anyone else looking for the answer:

<form class="search" action="<?php echo home_url( '/' ); ?>">
        <input type="search" name="s" placeholder="Search&hellip;">
        <input type="submit" value="Search">
        <input type="hidden" name="post_type" value="custom-post-type">

Obviously you will need to replace the value "custom-post-type" with your own custom post type.

  • Kudos bro! You saved my day! Sep 14, 2017 at 11:54
  • That did the trick for me, also if you want to include several post types you can use several inputs with "post_type[]" name, for example if you want to search in both "product" and "post" types: <input type="hidden" name="post_type[]" value="product" /><input type="hidden" name="post_type[]" value="post" />
    – rAthus
    Sep 30, 2020 at 13:38

A more elegant solution would be to modify the main query itself by using the pre_get_posts action.


function my_pre_get_posts($query) {

    if( is_admin() ) 

    if( is_search() && $query->is_main_query() ) {
        $query->set('post_type', 'custom-post-type-name');


add_action( 'pre_get_posts', 'my_pre_get_posts' );

This would require no change in the template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.