Created
March 13, 2012 20:08
-
-
Save jdolan/2031238 to your computer and use it in GitHub Desktop.
Drupal 7: Traversable taxonomy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Loads the specified terms, adding taxidermy-specific fields. | |
* | |
* @param array $tids | |
* The taxonomy term IDs. | |
* | |
* @return array | |
* The array of terms. | |
*/ | |
function _taxidermy_load_multiple(array $tids) { | |
$terms = taxonomy_term_load_multiple($tids); | |
foreach ($terms as $term) { | |
$term->parent = NULL; | |
$term->children = array(); | |
} | |
return $terms; | |
} | |
/** | |
* Construct an ordered tree of taxonomy terms for the specified vocabulary. | |
* | |
* @param mixed $vid | |
* The vocabulary ID. | |
* | |
* @return array | |
* An array of first-level terms, each with their children set. | |
*/ | |
function taxidermy_get_tree($vid) { | |
$tree = array(); | |
// query for all terms in the vocabulary | |
$query = db_select('taxonomy_term_data', 't'); | |
$query->join('taxonomy_term_hierarchy', 'h', 't.tid = h.tid'); | |
$query->fields('t', array('tid')); | |
$query->fields('h', array('parent')); | |
$query->condition('t.vid', $vocabulary->vid); | |
$query->orderBy('t.weight'); | |
// load the terms and prepare them for rendering | |
$result = $query->execute()->fetchAllAssoc('tid'); | |
$terms = _taxidermy_load_multiple(array_keys($result)); | |
// merge child terms to their parents, push top-level terms into the tree | |
foreach ($result as $row) { | |
$term = $terms[$row->tid]; | |
if ($row->parent) { | |
$parent = $terms[$row->parent]; | |
$term->parent = $parent; | |
$parent->children[] = $term; | |
} | |
else { | |
$tree[] = $term; | |
} | |
} | |
// insert any post-processing you require here, such as resolving term | |
// depth, term links, or backing the results into a cache bin | |
return $tree; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment