Let me first say that I'm no expert in Drupal. But in stumbling around various taxonomy functions, it seems that Drupal sometimes treat hierarchical terms a little inconsistently. You can tag something (let's say node/32) with Argentina, but you don't have to tag it with its parent term (South America, say). Which makes all the sense in the world. It's good to have that flexibility.
However, if you want to know how many nodes have been tagged as South America (using taxonomy_term_count_nodes()) node/32 will be included in that count, even though it isn't tagged as South America.
I'm proposing a simple, extra parameter to taxonomy_term_count_nodes(). It would not change any existing calls to the function, but would allow users to access counts for just that term, rather than counts for that term + any/all descendent terms. E.g.:
<?php
function taxonomy_term_count_nodes($tid, $type = 0, $children = TRUE) {
static $count;
if (!isset($count[$type])) {
// $type == 0 always evaluates TRUE if $type is a string
if (is_numeric($type)) {
$result = db_query(db_rewrite_sql('SELECT t.tid, COUNT(n.nid) AS c FROM {term_node} t INNER JOIN {node} n ON t.vid = n.vid WHERE n.status = 1 GROUP BY t.tid'));
}
else {
$result = db_query(db_rewrite_sql("SELECT t.tid, COUNT(n.nid) AS c FROM {term_node} t INNER JOIN {node} n ON t.vid = n.vid WHERE n.status = 1 AND n.type = '%s' GROUP BY t.tid"), $type);
}
$count[$type] = array();
while ($term = db_fetch_object($result)) {
$count[$type][$term->tid] = $term->c;
}
}
$children_count = 0;
if ($children) { // include children (actually any/all descendents) in count
foreach (_taxonomy_term_children($tid) as $c) {
$children_count += taxonomy_term_count_nodes($c, $type);
}
}
return $children_count + (isset($count[$type][$tid]) ? $count[$type][$tid] : 0);
}
?>
I'm happy to provide a patch, I just first want to see if this makes sense. Or am I missing something?
Comments
Comment #1
crookednumber commentedThis is pretty much a dupe of #204289: taxonomy_term_count_nodes returns wrong count for duplicate children, may not cache right either, though I'm curious to see how this plays out in #144969: taxonomy_term_count_nodes returns wrong count (+ tests). I'm wondering if these concerns (nodes tagged with a child term -- but not the parent -- are counted toward the parent count) are addressed.