Displaying clickable popular tags
How to create a list of the most frequently used tags in Drupal, with database query optimization.
We recently worked on creating a list of tags most frequently used by visitors (it is a question-answer forum), with the number of tags specified by the site administrator, with a choice of ‘0’ or a blank field indicating that all terms from a vocabulary be displayed. An important part of the implementation was generating the correct database query. After a couple of attempts, the following module was written (it is a hook_form_alter with the alteration being applied to the taxonomy through this function):
define('SQL_POPULAR_TERMS', 'SELECT td.tid, td.name, COUNT(tn.tid) FROM term_data td LEFT JOIN term_node tn ON (tn.tid = td.tid) WHERE td.vid = %d GROUP BY td.tid ORDER BY COUNT(tn.tid) DESC LIMIT %d');
define('SQL_POPULAR_TERMS_UNLIMITED', 'SELECT td.tid, td.name, COUNT(tn.tid) FROM term_data td LEFT JOIN term_node tn ON (tn.tid = td.tid) WHERE td.vid = %d GROUP BY td.tid ORDER BY COUNT(tn.tid) DESC');
function _sqe_get_popular_terms($vid, $count = NULL) {
if(is_null($count)) {
$count = variable_get('sqe_popular_tag_limit', 10);
}
if(empty($count)) {
$query = db_query(SQL_POPULAR_TERMS_UNLIMITED, $vid);
} else {
$query = db_query(SQL_POPULAR_TERMS, $vid, $count);
}
$terms = array();
while ($row = db_fetch_array($query)) {
$terms[$row['tid']] = $row['name'];
}
return $terms;
}
With a little bit of styling (we made the tags look like buttons and added an element type ‘a’ to them to make the default behaviour on hover appear to be ‘click’), the tags look invitingly clickable.