[WordPress] How to display only specific custom posts in search results

Here’s how to make WORDPRESS site search show only specific custom post types in search results.

Want to do

  • Show only specific custom post types in search results
  • Leave the entire search within the site

Code

[template].php

<form id="form" class="" action="<?php echo home_url(); ?>/" method="get">
<input name="s" type="text" placeholder="Keyword"/>
<input type="hidden" name="post_type" value="[custom post name]">
<button type="submit">検索</button>
</form>

search.php

<?php
if ( !empty( $_GET[ 'post_type' ] ) ) {
global $query_string;
query_posts( $query_string . "&post_type=" . $_GET[ 'post_type' ] );
}
?>
<?php if(have_posts()): ?>
<?php while(have_posts()): the_post(); ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<?php else : ?>
<p>Nothing</p>
<?php endif; ?>

 

記事がお役に立ちましたらシェアお願いします!