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

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

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(); ?>
                <li>
                  <?php if ( has_post_thumbnail() ) { ?><div class="post-image"><a href="https://wordpress.stackexchange.com/questions/248983/<?php echo get_permalink(); ?>"><?php the_post_thumbnail('thumbnail');?></a></div><?php }?>
                                    <div class="post-content">
                                    <h3><a href="https://wordpress.stackexchange.com/questions/248983/<?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>
                                </div>
                </li>
             <?php } ?>
             </ul>
         <?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( "https://wordpress.stackexchange.com/" ); ?>">
        <input type="search" name="s" placeholder="Search&hellip;">
        <input type="submit" value="Search">
        <input type="hidden" name="post_type" value="custom-post-type">
</form>

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

Leave a Reply

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