I was looking for a clean way to group my search results by posttype. I currently have 3 post types: Page, Post and Glossary. After a long search this answer in this thread got me what I needed.
The only problem is that there is no check for when a post type has no search results. If a post type has 0 results, e.g. Glossary, it still shows the post type title (and the container around the post type). I want the post type li.search-results-post-type-item
to be hidden in that case.
I am not looking for a css/js hacky display: none;
solution. I can't imagine this can't be done with PHP.
Thanks in advance!
Current situation
Posts
- Post search result 1
- Post search result 2
- etc.
Pages
- Page search result 1
- Page search result 2
- etc.
Glossary
(empty)
Desired situation
Posts
- Post search result 1
- Post search result 2
- etc.
Pages
- Page search result 1
- Page search result 2
- etc.
My code so far:
<?php
$search_query = new WP_Query(
array(
'posts_per_page' => 10,
's' => esc_attr( $_POST['keyword'] ),
'paged' => $paged,
'post_status' => 'publish'
)
);
if( $search_query->have_posts() ) : ?>
<div class="search-suggestions-list-header">
<?php echo $search_query->found_posts.' results found'; ?>
</div>
<ul class="search-results-list">
<?php
$types = array( 'post', 'page', 'glossary' );
foreach( $types as $type ) : ?>
<li class="search-results-post-type-item post-type-<?php echo $type ?>">
<header class="post-type-header">
<h5 class="post-type-title">
<?php
$post_type_obj = get_post_type_object( $type );
echo $post_type_obj->labels->name
?>
</h5>
</header>
<ul class="search-results-list">
<?php
while( $search_query->have_posts() ): $search_query->the_post();
if( $type == get_post_type() ) : ?>
<li class="search-results-list-item">
<h4 class="entry-title"><?php the_title();?></h4>
</li>
<?php
endif;
endwhile;
wp_reset_postdata();
?>
</ul>
</li>
<?php endforeach; ?>
</ul>
<?php else:
echo '<div class="search-suggestions-no-results">
<p>' . __('Sorry, no results found', 'text-domain') . '</p>
</div>';
endif;