0
votes

In a Drupal 7 block, I'm trying to list the taxonomy terms of a particular vocabulary in an unordered list, and also have any published nodes that are part of that taxonomy term as children.

Example:

Say I have a Vocabulary called Products, which has the taxonomy terms Beer, Wine, & Whiskey. Say Beer has 2 content nodes attached to it (Guinness & Budweiser) and so on.

It should end up looking like this:

  • Beer (2)
    • Guinness
    • Budweiser
  • Wine (2)
    • Pinot Noir
    • White Zinfandel
  • Whiskey (3)
    • Jack Daniels
    • Makers Mark
    • Crown Royal

I've figured out how to display "just" the taxonomy terms with the count, but cannot figure out how to print all published nodes that tie to each term. Here's what I got:

<?php

$vid = 1; //vocabulary id

$query = "SELECT tid, name, count
FROM (
SELECT td.tid AS tid, name, COUNT(td.tid) AS count
FROM taxonomy_term_data AS td
JOIN taxonomy_index AS tn
  ON td.tid = tn.tid
JOIN node AS n
  ON n.nid = tn.nid
WHERE td.vid = ". $vid ."
  AND n.status = 1
GROUP BY td.tid
ORDER BY count DESC
) AS t
ORDER BY name ASC";

$result = db_query($query);

print '<ul>';   
foreach($result as $term) {
if ($term->count > 0) {
  print '<li>';
  echo l($term->name, "taxonomy/term/$term->tid").' ('.$term->count.')';
  print '</li>';
}
}
print '</ul>';    

?>

This will produce the following output:

  • Beer (2)
  • Wine (2)
  • Whiskey (3)

But how do I make children of these taxonomy terms show published nodes that are part of that taxonomy term?

Any ideas?

Thank you

2
why are you not using views to accomplish this? - mmiles
I'm not sure if I can do this with Views. Could you explain any more details to help me out? - WebMW

2 Answers

0
votes

You can definitely do this with views. Use a "fields" type view. Add your node title and "All taxonomy terms" (filtered by your vocab) as fields. Add filters that specify not published, and your desired node type. In the format settings of your view, set "grouping field" to your taxonomy term. Optionally specify sorts. Typically I sort by the term, then node title.

0
votes