3

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="<?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>
                                </div>
                </li>
             <?php } ?>
             </ul>
         <?php } ?>

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

9

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">
</form>

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

6

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

<?php 

function my_pre_get_posts($query) {

    if( is_admin() ) 
        return;

    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, privacy policy and cookie policy

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