I want to group my search results to post types. I was able to do it by using foreach with an array of post types that I want but it also displays the ones that doesn't have any results. Here's my code taken from another thread.
<?php
if( have_posts() ){
$types = array('post', 'videos', 'graphics', 'photos');
foreach( $types as $type ){?>
<div class="card">
<div class="card-header">
<h4><?=$type;?></h4>
</div>
<div class="card-body">
<div class="type-<?=$type;?> row row-cols-1 row-cols-sm-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-3">
<?php
while( have_posts() ){
the_post();
if( $type == get_post_type() ){
echo get_template_part('template-part/content', $type);
}
}
rewind_posts();
?>
</div>
</div>
</div>
<?php
}
}
?>
Right now, it displays as:
Post
- post 1
- post 2
Graphics
Videos
- Videos 1
- Videos 2
Photos
How can I remove the Graphics, Photos in the header if graphics and photos type doesn't have anything to show?
foreach( $types as $type ){?>
loop. When you have a post, if $first == true then emit the card-header and set $first = false. At the end of the loop if $first == false then we have had posts in this category so generate the close div.