Skip to content

Instantly share code, notes, and snippets.

@interactiveRob
Forked from galengidman/search.php
Last active February 9, 2021 19:34
Show Gist options
  • Save interactiveRob/2d64bfd94f750c0e334a481e36417753 to your computer and use it in GitHub Desktop.
Save interactiveRob/2d64bfd94f750c0e334a481e36417753 to your computer and use it in GitHub Desktop.
WordPress search form & results for custom post type
<?php
// check to see if there is a post type in the URL
if ( isset( $_GET['post_type'] ) && $_GET['post_type'] ):
$filtered_posts = new WP_Query( array(
'post_type' => $_GET['post_type'],
'posts_per_page' => 12,
'orderby' => 'post_date',
's' => $_GET['s'],
));
if(have_posts($filtered_posts)):
while(have_posts($filtered_posts)): the_post();
$content = get_the_content();
$excerpt = wp_trim_words(content, 22, '...');
?>
<div class="search-result-item">
<a href="<?= get_the_permalink(); ?>">
<h2> <?= get_the_title(); ?> </h2>
</a>
<div class="search-result-item__excerpt">
<?= $excerpt ?>
</div>
</div>
<?php
endwhile;
else:
echo 'Sorry. We did not find any articles that match ' . $_GET['s'];
endif;
endif;
?>
<!-- default search results code here -->
<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="blogcovid">
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment