Community Documentation

Comma separated list of terms within a vocabulary with links and number of nodes

Last updated May 17, 2009. Created by Sverre on September 15, 2006.
Edited by bekasu, Heine, pwolanin. Log in to edit this page.

This snippet produces a comma separated list of terms within a given vocabulary, including links to the terms and the number of nodes.
e.g. Term 1 (4), Term 2 (5), Term 3 (6)
Change $vid as required.

<?php
// This snippet produces a comma separated list of terms within a given vocabulary
// Includes links to terms and number of nodes.
// Shared by Sverre - September 2006
// Drupal 4.7 tested

$vid = 1; // Change to appropriate vocabulary id

$result = db_query(db_rewrite_sql('SELECT t.tid, t.name, COUNT(*) AS count , parent FROM {term_data} t INNER JOIN  {term_hierarchy} h ON t.tid = h.tid INNER JOIN {term_node} tn USING (tid) INNER JOIN {node} n USING (nid) WHERE t.vid = %d  GROUP BY t.tid, t.name ORDER BY weight, name', 't', 'tid'), $vid);
$items = array();
while (
$category = db_fetch_object($result)) {
 
$items[] = l($category->name .' ('. $category->count .')', 'taxonomy/term/'. $category->tid);
}

print
str_replace(' | ', ', ', theme('links', $items));
?>

Unknown Column Error

An error "Unknown column 'col_name' in 'on clause'" may occur if you are use this snippet with MySQL > 5.0.x. There are some changes in join proccessing from 5.0.12. I can propose my simple query to solve this error. This query is only for plain vocabularies. Change $result variable to:

$result = db_query(db_rewrite_sql('SELECT t.tid, t.name, t.description, COUNT(*) as count FROM {term_data} t INNER JOIN {term_node} tn ON t.tid = tn.tid WHERE t.vid = %d  GROUP BY t.tid, t.name ORDER BY weight, name', 't', 'tid'), $vid);

About this page

Drupal version
Drupal 4.7.x

Reference

Drupal’s online documentation is © 2000-2012 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.