Get Taxonomy Terms by Count
This function returns an array of taxonomy term objects. It is much like taxonomy_get_tree(), and it does in fact use this function. We had a client that wanted a grid of product categories with an image for each term, but only for terms that have at least X associated nodes. This problem was solved using the function below, as well as another custom function to alter the views query (I’ll post about this later).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/** * Returns an array of taxonomy terms that have been associated with at least X nodes * * @param $vid * The vocabulary id * @param $min_items * The minimum number of items that have been associated with this term * @return * An array of taxonomy term objects */ function mymodule_get_terms_by_count($vid, $min_items = -1){ $terms = taxonomy_get_tree($vid); $items = array(); foreach ($terms as $term) { $count = taxonomy_term_count_nodes($term->tid); if ($count == -1 || $count >= $min_items) { $items[] = $term; } } return $items; } |
I’d like to also mention that I toyed with the idea of adding a $max_items variable. It’s simple enough to do, but I figured (maybe incorrectly) that you wouldn’t ever need to say, “Give me all terms that have between 10 and 30 associated records.”