Search code examples
drupal-7

Listing Drupal taxanomy terms


I want to list a vocabulary terms as following format

<ul id="vid1">
<li>term1</li>
<li>term2
  <ul>
    <li>term2-child1</li>
    <li>term2-child2</li>
  </ul>
</li>
<li>term3
  <ul>
    <li>term3-child1</li>
    <li>term3-child2</li>
  </ul>
</li>
</ul>

How can I modify the following code to meet my requirement

<?php
$vid = 1; 
$terms = taxonomy_get_tree($vid); 
print_r($terms);
echo "<ul>";
foreach ( $terms as $term ) {
$count = db_query("SELECT COUNT(nid) FROM {taxonomy_index} WHERE tid = :tid ", array(':tid' => $term->tid))->fetchField();
print "<li>".$term->name." (".$count.")</li>";
}
echo "</ul>";
?>

Solution

  • $vid = 1;
    
    $tree = taxonomy_get_tree($vid);
    print '<ul id="vid1">';
    
    foreach($tree as $key=>$term) {
     if($term->parents[0]==0) {
      print '<li>'.$term->name;
    
      $childrens = taxonomy_get_children($term->tid);
      print '<ul>';
    
      foreach($childrens as $children) {
        print '<li>'.$children->name.'</li>';
      }
      print '</ul></li>';
     }
    };
    
    print '</ul>';