Skip to content

Instantly share code, notes, and snippets.

@jdolan
Created March 13, 2012 20:08
Show Gist options
  • Save jdolan/2031238 to your computer and use it in GitHub Desktop.
Save jdolan/2031238 to your computer and use it in GitHub Desktop.
Drupal 7: Traversable taxonomy
<?php
/**
* Returns the menu items for the specified term and its children (recursively).
*
* @param $term
* The term instance.
*
* @return array
* The menu item(s), as a renderable array.
*/
function taxidermy_menu_items($term) {
$uri = entity_uri('taxonomy_term', $term);
$items = array('data' => l($term->name, $uri['path'], $uri['options']));
foreach ($term->children as $child) {
$items['children'][] = taxidermy_menu_items($child);
}
return $items;
}
/**
* Returns the rendered menu structure based on the default vocabulary.
*
* @return string
* The rendered menu.
*/
function taxidermy_menu() {
$menu = array('#theme' => 'item_list');
foreach (taxidermy_get_tree(1) as $term) {
$menu['#items'][] = taxidermy_menu_items($term);
}
return render($menu);
}
<?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