There's probably a right way or an easy way to do this, but I've been up and down the forums and over the Views documentation, and I can't find anything on this. A simple example of what I'm trying to do is this:

Say I have a node type, called "dog". I have a category called "hair length". I have 2 terms in the category, "short hair" and "long hair". And let's say I have 5 dogs tagged "short hair", and 3 tagged "long hair". I want to show this to the user:

long hair: 3
short hair: 5

I can't find a function or a way to do it directly via db_query. I'm going cross-eyed from all the forum posts and documentation. HELP!!!

Comments

mooffie’s picture

There're two methods to do this.

The first one is not to code it yourself (using PHP), but to use 'Views' instead:

Create a view to show the nodes. Then add an arguments of type taxnomy. In its 'default' column choose 'summary'.

The second method is to code it yourself, using PHP and SQL. The SQL statement is:

SELECT
       td.name, COUNT(*) AS count
FROM
       `node` n
INNER JOIN
       `term_node` tn ON tn.nid = n.nid
INNER JOIN
       `term_data` td ON td.tid = tn.tid
WHERE
       n.type = 'dog'
GROUP BY
       td.tid

Feed this to your phpMyAdmin (or similar tool) to see the magic. If you're satisfied with the result, convert it to PHP:

Let's suppose the above SQL is contained in a $sql varible (should replace backquotes with "{}", for table prefixing). Then you do:

$res = db_query($sql);
while ($obj = db_fetch_object($res)) {
  print "$obj->name ($obj->count) <br />";
}

(Type this into a node; choose the PHP filter.)