Pages

Tuesday, April 10, 2012

Drupal 7: Show Nested Taxonomy Terms With Links In a Node

If you need to create a page or node with the nested taxonomy terms (aka Categories) with links, you can use this code:




<?php
            // The ID of the taxonomy vocabulary for which you'd like to create a nested list
            $vid = 6;
            // The ID of the parent term of the categories you want to create the nested list
            $tid = 24409;
            $depth = 0;
            $num_at_depth = 0;
            $tree = taxonomy_get_tree($vid, $tid);


            print "<ul class=\"menu\">\n<li>";
            foreach ($tree as $term) {
            $diffdepth=0;
              if ($term->depth > $depth) {
                print "\n<ul>\n<li>";
                $depth = $term->depth;
                    $num_at_depth = 0;
              }
              if ($term->depth < $depth) {
                $diffdepth= $depth -$term->depth;
                while ($diffdepth > 0){
                    print "</li>\n</ul>\n";
                    $diffdepth -- ; 
                }
                    $depth = $term->depth;
              }
              if (($term->depth == $depth) && ($num_at_depth > 0)) {
                  print "</li>\n<li>";
                }
              print l($term->name, 'taxonomy/term/' . $term->tid);
                $num_at_depth ++;
            }
            print "</li>\n</ul>\n";
?>

I'm currently working on adding the node count on each term but so far I haven't had any success with it.

Reference: http://drupal.org/node/223675

No comments:

Post a Comment