Post Pic

WordPress trick: function to get tags related to category

Do you ever wanted to be able to get tags related to one (or more) specific category? If yes, I’m pretty sure you’ll be delighted with this very cool tip.

First, here is the function you have to paste in your function.php file:

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;
}

Once you have pasted the function, you can use it in your theme:

$args = array('categories' => '12,13,14');
$tags = get_category_tags($args);

Credits: WordPress Codex

13 Responses

Oct 12 2009 18:33

I was looking for this a few weeks ago and could not find one. Thanks for this.

Oct 12 2009 23:51

This would be VERY nice addon to WP admin, when posting new post, and slecting category-to display only used tags on that/those selected categories… SO no need to remeber all tags and so on.

Oct 13 2009 00:08

And it’s not working.

Oct 13 2009 00:17

Sorry it works.. i forgot to remove wp from query :)

Oct 14 2009 10:38

Hi guys this really seems wonderful, How about an example of a loop as how to use it , mmmmmmmm say for retards like me.
Because the author really tells it in the end how to use it , all i wanted to know was that is that something that we need to paste in php tags and we are done a special loop needs to be created.

Looking forward to the answer. Thanks a lot.

Oct 22 2009 08:42

I think this very cool tips…

and i think we can achieve this by using wordpress taxonomy features..

thank you for this…

Oct 26 2009 19:47

Hi do you know if it’s possible to put a variable for the category in your code. I wonder know if it’s possible to insert this function in the category template so that it will display only the tag for the category display (eventualy for its parent too).
Thanks for your input on that

Dec 17 2009 04:27

Wordpress rookie here. Where do I post the “$args & $tags”?

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required