Using Drupal's taxonomy, I found an instance where I wanted to get all the terms that were populated in a particular category. Using Drupal's taxonomy feature, I create a vocabulary and then create terms I then assign to the vocabulary. In my case, I want to treat the vocabulary as a master category,if you will, and the terms as sub-categories.
Drupal allows you to get related terms to your vocabulary, if you know the vid. However, instead of passing the vocabulary id I wanted to use my master category name (vocabulary), and get it's sub-categories (the terms). This is because looking up the vid (Vocabulary ID) every time can be a major pain. Of course, there is a potential drawback here if more than one vocabulary is created with the same name (if it can be done; I never tried it and am not sure if Drupal dis-allows it).
So, here's a small function you can put in your themes template.php file to get an object using the category name:
function hook_get_terms_by_vocabulary( $name ){
if ( $query = db_query( "SELECT term_data.*
FROM {term_data} LEFT JOIN {vocabulary} ON
vocabulary.vid=term_data.vid WHERE
vocabulary.name='%s'", $name ) ){
return $query;
}
return false;
}
Change the "hook" in "hook_get_terms_by_vocabulary" to your theme's name and save.
What you get back is a db object. You can loop through the return result by doing:
while( $term = hook_get_terms_by_vocabulary( 'My Vocabulary Name' ){ print $term->name . "<br />"; }.
Other useful properties in the object are $term->tid and $term->vid (term id and vocabulary id repectively).
