Very often I and other module developers (for example, Ubercart) need to count nodes for more than one types and they need to call taxonomy_term_count_nodes() one time for each type and this generates more than one SQL query.
I think that little modifications to this function doesn't slows Drupal core but adds more functionality to Drupal API.
For example, we can modify function like there:
function taxonomy_term_count_nodes($tid, $type = 0) {
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'));
}
elseif(is_array($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 AND n.type in ('%s') GROUP BY t.tid", implode("','",$type));
}
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);
}
while ($term = db_fetch_object($result)) {
$count[$type][$term->tid] = $term->c;
}
}
$children_count = 0;
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);
}
Comments
Comment #1
Susurrus commentedYou should use
db_placeholders()instead of that implode and also roll into a patch versus just attaching code.Comment #2
catchNo longer exists in HEAD.