1

I am hoping to make a custom tag widget which displays all tags from a specific category. The code I am currently using is working correctly, but it is displaying duplicate tags. I would like to utilize array_unique() to remove any duplicates before printing the linked list of tags, but not sure how to pull out the tag slug and tag name after removing duplicates.

Here is my current code:

<?php
    query_posts('category_name=testing');
    if (have_posts()) : while (have_posts()) : the_post();
    $posttags = get_the_tags();
    if ($posttags) {
        foreach($posttags as $tag) {
            echo '<a href="' . home_url('/tag/' . $tag -> slug) . '">' . $tag -> name . '</a> ';
        }
    }
    endwhile; endif; 
?>

1 Answer 1

4

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.

2
  • This works great, and thank you so much for sharing the link regarding why not to use query_posts, very informative.
    – user13286
    Commented Apr 17, 2015 at 14:39
  • @TheDeadMedic what if we want to list unique categories under a tag? do you have any possible solution? I am trying to list categories under a tag but I cant make them unique.
    – Rain Man
    Commented Nov 2, 2016 at 14:32

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.