0

What's the best way to only show the name of a taxonomy once? I use a taxonomy called show_category that has three categories: News, Reviews and Uncategorized. I have six posts: three in News, one in reviews and two in uncategorized. They are displayed as the following:

News (name of category in taxonomy) News item 1 News (name of category in taxonomy) News item 2 News (name of category in taxonomy) News item 3 Reviews (name of category in taxonomy) Review item Uncategorized (name of category in taxonomy) tes Uncategorized (name of category in taxonomy) test 2

I'm looking for a way to only the name of category in a taxonomy only once like this:

News (name of category in taxonomy) News item 1 News item 2 News item 3 Reviews (name of category in taxonomy) Review item Uncategorized (name of category in taxonomy) Tes Test 2

Code of my loop:

<?php $postcount=0; while ( have_posts() ) : the_post(); 
$terms = wp_get_post_terms( get_the_ID(), 'show_category');
foreach ($terms as $t):
echo $t->name;
endforeach;?>
<div id="<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_title();?>
</div>
<?php endwhile; ?>
1
  • 1
    Can you fix your codes formatting so that multiple lines of PHP don't have unnecessary opening and closing tags, and statements are each on their own lines? It's difficult to read when everything is bunched up together :(
    – Tom J Nowell
    Oct 1 '19 at 20:19
1

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..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.