Get Tags Based On The WordPress Category
WordPress does a lot of things really well. Sometimes you want to do something that seems simple but requires some tweaking and a bit of hacking. If you want to get specific and display tags based on specific categories of your choosing, this code will let you do it.
<?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
?>
Here is another method that you can use to take it even farther.
Note: If you use the code below you do not need to include the other snippet above.
In your theme’s functions.php insert the following function:
function get_category_tags($args) {
global $wpdb;
$tags = $wpdb->get_results
("
SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name, null as tag_link
FROM
wp_posts as p1
LEFT JOIN wp_term_relationships as r1 ON p1.ID = r1.object_ID
LEFT JOIN wp_term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
LEFT JOIN wp_terms as terms1 ON t1.term_id = terms1.term_id,
wp_posts as p2
LEFT JOIN wp_term_relationships as r2 ON p2.ID = r2.object_ID
LEFT JOIN wp_term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
LEFT JOIN wp_terms as terms2 ON t2.term_id = terms2.term_id
WHERE
t1.taxonomy = 'category' AND p1.post_status = 'publish' AND terms1.term_id IN (".$args['categories'].") AND
t2.taxonomy = 'post_tag' AND p2.post_status = 'publish'
AND p1.ID = p2.ID
ORDER by tag_name
");
$count = 0;
foreach ($tags as $tag) {
$tags[$count]->tag_link = get_tag_link($tag->tag_id);
$count++;
}
return $tags;
}
In your theme document call the function as follows. Notice it accepts multiple category id’s:
$args = array( 'categories' => '12,13,14' ); $tags = get_category_tags($args);
This will return an array that you could do the following with:
$content .= "<ul>";
foreach ($tags as $tag) {
$content .= "<li><a href=\"$tag->tag_link\">$tag->tag_name</a></li>";
}
$content .= "</ul>";
echo $content;
.via { WordPress Forums }





Pingback by Actualización de Twitter para 2009-11-07 | Jose Orestes — November 7, 2009 @ 7:27 am
[...] @nazareth: Get tags based on the #Wordpress category: http://wpswitch.com/?p=355 [...]