Here’s the code, rewriten from posts and categories to custom post types and taxonomy terms.
Thanks to @PieterGoosen for providing the first version.
<?php
$args = array(
'post_type' => 'produkty', // your CTP name
'meta_key' => 'produkt_nowosc', // custom meta key for displaying, in my case: the newest product in offer
'meta_value' => 'tak', // field above set to 'yes'
'posts_per_page' => -1
);
$query = new WP_Query($args);
$q = array();
while ( $query->have_posts() ) {
$query->the_post();
// displaying the content of product box etc.
$a="<a href="". get_permalink() .'">' . get_the_title() .'</a>';
$terms = wp_get_post_terms( $post->ID, 'kategorie_produktow', $args );
foreach ( $terms as $term) {
$term_link = get_term_link( $term );
$b = '<span>'.$term->name.'</span>';
}
$q[$b][] = $a;
}
wp_reset_postdata();
foreach ($q as $key=>$values) {
echo $key;
echo '<ul>';
foreach ($values as $value){
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
?>