Collapsible top level taxonomy menu list

I've written a block snippet for 5.0 which will take the top level terms of a vocabulary and make them collapsible(.js) so that child terms are hidden by default. If anyone is interested there's a demo on my site ATM for a better idea of what i'm doing.

The structure of the menu is:

Test Menu(vocab)
-->Design (a top level/parent term and submenu title)
*Domains (a child term to Design term)
*Hosting (ditto)
*domain sub term (a child of the Domains child term should be indented)

Many thanks to http://www.xweb.com.au for this code which is also found - http://drupal.org/node/109185

Paste it into a block. Edit the $vocabulary --vv. Display the block where you need it. Repeat for however many vocabs you have.

Snippet:
<?php
// accordion taxonomy menu
// by Chris Herberte
// ** don't forget to change $vocabulary --vv
//
$vocabulary = #; // <-- change # to your vid (e.g 1)

drupal_add_js('misc/collapse.js');
$lastdepth = 1;
$topoflist = 1;
$nid = 0;

if (
arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2) ) {
 
$nid = arg(1);
 
$terms = taxonomy_node_get_terms($nid);
 
rsort($terms);
 
$tid = $terms[0]->tid;
}
elseif (
arg(0) == 'taxonomy' && arg(1) == 'term') {
 
$terms = preg_split('/[+ ,]/', arg(2));
 
$tid = $terms[0];
}

$parents = taxonomy_get_parents($tid);
foreach (
$parents as $parent) {
$i++;
}

$tree = taxonomy_get_tree($vocabulary);

foreach (
$tree as $term) {

  if (
$lastdepth == 1 && $term->depth == 0 ) {
   
$legend = $term->name;
    if (
$topoflist == 0) {
      print
"</ul></div></fieldset>";
    }

    if (
$term->tid == $parent->tid) {
       print
"<fieldset class='collapsible'><legend>$legend</legend><div class='description'><ul>";
    }
    else {
       print
"<fieldset class='collapsible collapsed'><legend>$legend</legend><div class='description'><ul class='menu'>";
    }
   
$topoflist = 0;
  }

  if (
$term->depth > 0) {

    if (
$term->tid == $tid) {
       print
"<li class='collapsed' id='darker'>" . l($term->name, "taxonomy/term/$term->tid") . "</li>\n";
    }
    else {
       print
"<li class='leaf notdarker'>" . l($term->name, "taxonomy/term/$term->tid") . "</li>\n";
    }
  }

 
$lastdepth = $term->depth;
}
print
"</ul></div></fieldset>";
?>

Comments

Chris Herberte@drupal.org

Drupalized -- does the same as above.

<?php
$vid
= 1;

$tree = taxonomy_get_tree($vid, 0, -1, 1);

foreach (
$tree as $term) {
 
$items = array();
 
$children = taxonomy_get_children($term->tid, $vid, 'tid');
  foreach (
$children as $child) {
   
$items[] = l($child->name, 'taxonomy/term/'. $child->tid);
  }
 
$fieldset = array(
   
'#title' => $term->name,
   
'#collapsible' => TRUE,
   
'#collapsed' => TRUE,
   
'#value' => theme('item_list', $items),
   
'#attributes' => array('class' => 'accordian'),
  );
  print
theme('fieldset', $fieldset);
}
?>