views:

858

answers:

4

I want to create a list of category terms (contained within a block), with each term to be followed by a count of the number of nodes with that term, e.g.:

Cats (5)
Dogs (4)
Elephants (2)

There are a number of modules that create whole lists like this dynamically, but I've found they all have drawbacks for my purposes. I literally just need something like this:

<ul>
<li><a href="mylink">Cats</a> (<?php ...some code... ?>)</li>
<li><a href="mylink">Dogs</a> (<?php ...some code... ?>)</li>
<li><a href="mylink">Elephants</a> (<?php ...some code... ?>)</li>
</ul>

I.e. I only need the count to be dynamic, not the whole list (this is OK because the terms themselves will not change). I've heard that the Drupal function taxonomy_term_count_nodes() may be useful, but I can't find any simple information regarding its implementation.

+6  A: 

What information do you want regarding its implementation? The documentation seems pretty clear...

<?php print taxonomy_term_count_nodes($term_id); ?>
ceejayoz
Well, it's clear now I know you can do it like that. Thanks!
james6848
+2  A: 

I've done that a few times. IMO you're better off using Views to create a Node view that just lists Taxonomy terms, and then use the http://drupal.org/project/views_groupby module to put the number of nodes with that term beside the term. The example at the views_groupby documentation tells you what you need to know.

Your custom module will obviously be a bit more flexible, but ultimately unnecessary given the above.

Mike Crittenden
+1  A: 

I'm also not sure what information you are missing in the documentation - maybe an example helps. The following will create an ordered list of all terms within a vocabulary, with their node counts attached (untested, so there may be typos).

// Adjust this to the id of the vocabulary holding your terms
$vid = 1;
// Grab all terms in that vocabulary
$terms = taxonomy_get_tree($vid);
$items = array();
foreach ($terms as $term) {
  // Get the number of (published) nodes with that term
  $count = taxonomy_term_count_nodes($term->tid);
  // Assemble your link text
  $text = $term->name . ' (' . $count . ')';
  // Set this to the path you want to link to (default term views used here)
  $path = 'taxonomy/term/' . $term->tid;
  // Turn the above into a rendered link
  $link = l($text, $path);
  // Add to items
  $items[] = $link;
}
// Render array as an ordered list
$list = theme('item_list', $items, NULL, 'ol');

print $list;
Henrik Opel
A: 

Does this apply if you want the taxonomy counts to be displayed in your menus, so if a user goes to the primary menu the drop down options will have their node counts?

evelyn

related questions