
Althought WordPress allow you to do lots of things by default, it didn’t allow you to display tags based on a selected category. Here is an useful code to be able to do so.

Althought WordPress allow you to do lots of things by default, it didn’t allow you to display tags based on a selected category. Here is an useful code to be able to do so.
Just paste this code wherever you need to display the list of tags that are specific to a particular category. Don't forget to replace the category name on line 2.
<?php
query_posts('category_name=work');
if (have_posts()) : while (have_posts()) : the_post();
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$all_tags_arr[] = $tag -> name; //USING JUST $tag MAKING $all_tags_arr A MULTI-DIMENSIONAL ARRAY, WHICH DOES WORK WITH array_unique
}
}
endwhile; endif;
$tags_arr = array_unique($all_tags_arr); //REMOVES DUPLICATES
echo '<pre>'.print_r($tags_arr, true).'</pre>'; //OUTPUT FINAL TAGS FROM CATEGORY
?>
Thanks to WordPress Forums for the tip!
† RIP Michael Jackson †
21 Responses
I had a busy time and I missed from you blog, now I must check you posts.
this code need some fixes
we should not use query_posts in this case, but the WP_Query object
http://codex.wordpress.org/Template_Tags/query_posts
also, if you use it, you may want to add “showposts=-1″ to the query so that the tags are collected from all the posts, and not only from the first set
Great code. Could you tell me how I can then display these tags as a cloud or a list? Thanks!
@Greg: Basically, you have to use a foreach instruction on the $tags_arr array.
Example:
foreach ($tags_arr as $tag) {
echo “<li>”.$tag.”</li>”;
}
Jean – thank you. That does help. I’m not good enough at PHP to figure this out on my own and appreciate the help. Would it be a lot of work to make code that would display a category-specific tag cloud with links to the tag archives, etc.?
Thank you.
This Query will be perfect if tags name will be cliquable. Is there a way to make a tag link easily ?
Thanks !
Thanks a lot buddy to provide me such a valuable code. I would definitely use it in my blog and after the implementation will let you know..
I got this working, but I see a flaw.
If the tags have a ’space’ the famous %20 shows it’s ugly head
I have tried to fix this but I keep breaking it, anyone fixed this issue?
(great bit of coding BTW)
I’d love to see this functioning as a drop list form element. The reason is that categories can contain a lot of posts and therefore many tags too. Seems like a drop list is ideal for accessing a large number of tags in a convenient and clean presentation.
name; //USING JUST $tag MAKING $all_tags_arr A MULTI-DIMENSIONAL ARRAY, WHICH DOES WORK WITH array_unique
}
}
endwhile; endif;
$tags_arr = array_unique($all_tags_arr); //REMOVES DUPLICATES
echo ”.print_r($tags_arr, true).”; //OUTPUT FINAL TAGS FROM CATEGORY
?>
With the above code we will get only tittle
i want there links
how should i get????
Thanks
Trackbacks: