Not the best, but works well for me: (you can use this instead of what’s in the question)
$postcount = 0;
//global $wp_query; // Uncomment if necessary.
// Group the posts by category.
$groups = [];
foreach ( $wp_query->posts as $i => $p ) {
$terms = wp_get_post_terms( $p->ID, 'show_category' );
foreach ( $terms as $t ) {
if ( ! isset( $groups[ $t->term_id ] ) ) {
$groups[ $t->term_id ] = [];
}
$groups[ $t->term_id ][] =& $wp_query->posts[ $i ];
}
}
// And display the posts under their own category. Note though, that a post may
// appear twice if it's assigned to multiple categories.
global $post;
foreach ( $groups as $term_id => $posts ) {
$term = get_term( $term_id );
// Display the term/category name.
echo '<h3>' . esc_html( $term->name ) . '</h3>';
// And the category's posts.
foreach ( $posts as $post ) {
setup_postdata( $post );
?>
<div id="<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_title(); ?>
</div>
<?php
}
}
wp_reset_postdata();
PS: The h3
tags are just examples..