How to Get All Tags for a Category in Wordpress

Lately I’ve been doing some Wordpress plugin development for a project. I found myself needing a way to get all the tags associated with a particular category. Wordpress doesn’t offer this as a template tag, but its easy enough to query the database directly. I didn't find this anywhere in the Wordpress codex or in a search, so I thought I'd post it here:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?php

$sql = "SELECT name, slug
        FROM wp_terms
        JOIN wp_term_relationships
        ON wp_terms.term_id = wp_term_relationships.term_taxonomy_id
        JOIN wp_term_taxonomy
        ON wp_terms.term_id = wp_term_taxonomy.term_id
        WHERE wp_term_relationships.object_id IN (
        SELECT object_id FROM wp_term_relationships WHERE
        wp_term_relationships.term_taxonomy_id = %d)
        AND wp_term_taxonomy.taxonomy = 'post_tag'";

// $cat_number is the number of the category in question.

$sql = $wpdb->prepare($sql, $cat_number); 
$results = $wpdb->get_results($sql);

?>

Now you can iterate through the results and display them however you want. Note that I'm selecting the name and slug so I can print links to the tag page. Alter the query as you see fit.

Posted: August 25, 2009 / 0 comments

Comments