In a node I'm creating, there is a hierarchical select widget. The widget saves the 'deepest' term in a given taxonomy.

These terms come out in the $node->taxonomy array in tpl files.

I want to build the tree right back up to the last parent. How do I do this? What is the algorithm? I have a complete sphagetti mess that's not even worth posting here, right now. I have a feeling there's recursion involved somewhere, but I'm missing the specifics - pseudocode please?


I don't know of an API function that can do this but the following code should help:

$tid = 4; // Your term id

// Grab all of the parents of this term (including the term itself) 
// in reverse order.
$parents = array_reverse(taxonomy_get_parents_all($tid));

$tree = array();

// Get a reference to the root of the array. This reference will be updated
// in each iteration of the loop to refer to the array of children added to
// the term.
$ref = &$tree; 
foreach ($parents as $term) {
  // Add the current term to the relevant root/children array.
  $ref[$term->tid] = $term;

  // If the current term is NOT the original child term, we add an array of
  // children to the term and update the array reference to point to it.
  if ($term->tid != $tid) {
    $term->children = array();
    $ref = &$term->children;

By the time that loop has run the $tree variable will be a hierarchical representation of the original term's parents, with each child term in the children key of it's parent term object.

I've only tested this on terms that have a single parent; if you've got terms with multiple parents I think you'll struggle to get this to work.

  • Thank you! This worked exactly like I needed to, giving me exactly what I wanted. I just found out the childless terms and fed them to this loop, and it gave out a perfect tree I could recursively iterate through to display. You saved my life. – Aditya M P Apr 29 '12 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.