How to Display terms only if associated with a node
Hmm... I'd try something like this:

Change this part of your code:

foreach ($children as $term) {
  $output .= '&lt;li&gt;';
  $output .= l($term-&gt;name, 'taxonomy/term/' . $term-&gt;tid);
  $output .= '&lt;/li&gt;';
}


to something like this:

// Avoid unnecessary "Invalid foreach" errors showing up in the log:
if (!empty($children)) {
  // If not empty, run the foreach loop:
  foreach ($children as $term) {
    // Then check to see if any nodes exist for that term id:
    $number_of_nodes = taxonomy_term_count_nodes($term-&gt;tid);
    // If there ARE nodes...
    if ($number_of_nodes &gt; 0) {
      // ... then add them to the output:
      $output .= '&lt;li&gt;';
      $output .= l($term-&gt;name, 'taxonomy/term/' . $term-&gt;tid);
      $output .= '&lt;/li&gt;';
    }
  }
}


Hope that helps... :)