Drupal tag list block

tung's picture

I just implemented a tag list for the site, just like at the old Blogger site.

Trying to do this using views was a massive pain and wholly unsuccessful, so I turned directly to my best skill: programming. Blocks in Drupal allow insertion of PHP.

But it wasn't working. Anything I inserted would appear as code directly on the page. Then I realised I had to enable the PHP input filter module. Ugh.

Anyway, with a hint from Google, and peeking into the database schema myself, I was able to drum up this little baby. It'll list all the "terms" under a given "vocabulary", within Drupal's esoterically named "taxonomy" system.

<?php
  /**
   * Abstraction-breaking custom tag lister.
   * This block lists all tags under the given taxonomy vocabulary,
   * in order of frequency, and then name. The tags are hyperlinked.
   */
  $vocabulary_id = 8;
  $cutoff = 20;       // don't show results that don't pass the threshold
  $threshold = 1;     // after cutoff, don't show tags with counts below this
  $tag_query = "SELECT td.tid, td.name, COUNT(DISTINCT tn.nid) AS num " .
               "FROM term_data td, " .
               "     term_node tn " .
               "WHERE td.vid = %d AND " .
               "      td.tid = tn.tid " .
               "GROUP BY td.tid, td.name " .
               "ORDER BY num DESC, td.name ASC ";
  $result = db_query($tag_query, $vocabulary_id);
 
  if ($result) {
 
    print "<ul>";
    $results_so_far = 0;
    while ($row = db_fetch_object($result)) {
      $results_so_far++;
      if ($results_so_far > $cutoff && $row->num <= $threshold)
        break;
      print "<li>" .
            "<a href=\"/site/taxonomy/term/" . $row->tid . "\">" .
            $row->name .
            "</a>" .
            " (" . $row->num . ")" .
            "</li>";
    }
    print "</ul>";
 
  } else {
 
    print "Tags unavailable.";
 
  }
?>

Awesome.

::UPDATE::

Whoops, forgot the DISTINCT bit.