0

I have a custom taxonomy (item_tags) for tags available to a cpt (item).

How do I list the name+description of each tag in that taxonomy, and the linked title+excerpt of the posts assigned to each tag?

I've looked at a lot of examples, but not yet found anything that works.

1 Answer 1

0

To list names and descriptions you can use get_terms(). That will return an array with all terms. An example would be:

global $post;    
$terms = get_terms( array(
    'taxonomy' => 'item_tags',
    'hide_empty' => false,
) );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
    foreach ( $terms as $term ) {
        echo '<h2>' . $term->name . '</h2>';
        echo apply_filters( 'the_content', $term->description );
        $items = get_posts( array (
            'post_type' => 'item',
            'tax_query' => array(
                array(
                    'taxonomy' => 'item_tags',
                    'terms'    => $term->term_id,
                ),
            ),
        ) );
        foreach ( $items as $post ) {
            setup_postdata( $post );
            ?>
            <div>
                <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                <?php the_excerpt(); ?>
            </div>
            <?php
        }
    }
    wp_reset_postdata();
}

Hope it helps!

6
  • Thanks. It's very helpful - I've been struggling with this for many hours. I've edited my original post to make clear that rather than whole posts it's just a linked title+excerpt that I want to display. And I'm trying to understand how to amend your code accordingly (but as a novice, I don't expect it to be a quick thing).
    – glvr
    Commented May 6, 2018 at 15:56
  • I've edited to show the linked post title and the excerpt, @glvr. Commented May 7, 2018 at 16:07
  • Thanks. I don't want to be troublesome, but what I'm getting with the revised code is 'Tag name+description' - and in between each is 'Linked title+excerpt of the test page I'm using to display this'.
    – glvr
    Commented May 8, 2018 at 10:21
  • No problem @glvr. Give it a try now. Don't forget to add the initial global $post; Commented May 8, 2018 at 12:54
  • If it did help you don't forget to accept as the answer :) Thanks! Commented May 8, 2018 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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