Creating a unique, linked list of tags from a specific category?

You can build a stack of unique tags, then loop over them again to output. Couple of extra things though – never use query_posts. Secondly, you can be way more efficient in your querying and save a lot of memory in the process:

$post_ids = get_posts(
    array(
        'posts_per_page' => -1,
        'category_name'  => 'testing',
        'fields'         => 'ids', // Just get the ID's, save a hella lotta memory
    )
);

// Get and cache all post tags in one swoop
update_object_term_cache( $post_ids, 'post' );

// Build a unique index of tags for these posts
$tags = array();
foreach ( $post_ids as $post_id ) {
    if ( $post_tags = get_object_term_cache( $post_id, 'post_tag' ) ) {
        foreach ( $post_tags as $tag )
            $tags[ $tag->term_id ] = $tag;
    }   
}

// Show em!
foreach ( $tags as $tag ) {
    echo '<a href="' . get_term_link( $tag ) . '">' . $tag->name . '</a> ';
}

Update: Bug fixes as per this related answer.

Leave a Comment

tech