taxonomy_term_count_nodes

5 taxonomy.module taxonomy_term_count_nodes($tid, $type = 0)
6 taxonomy.module taxonomy_term_count_nodes($tid, $type = 0)

Count the number of published nodes classified by a term.

Parameters

$tid: The term's ID

$type: The $node->type. If given, taxonomy_term_count_nodes only counts nodes of $type that are classified with the term $tid.

Return value

int An integer representing a number of nodes. Results are statically cached.

File

modules/taxonomy/taxonomy.module, line 963
Enables the organization of content into categories.

Code

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'));
    }
    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;
  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

Drupal 7 equivalent

The function was removed from the API in Drupal 7.
There are a few different approaches in D7:

Here's a solution involving count on an EntityFieldQuery:

  $query = new EntityFieldQuery();
  $count = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'article')
    ->propertyCondition('status', 1)
    // Checks against the 'field_content_classification' term reference field.
    ->fieldCondition('field_content_classification', 'tid', 1, '=')
    ->count()
    ->execute();

Another solution might query the taxonomy_maintain_index_table directly.

Another Drupal 7 equivalent

I do use this function as a replacement which tries to resample taxonomy_term_count_nodes() for Drupal 7 as much as possible. I did ignore the children part though - did not check it's importance yet:

<?php
function custom_helper_taxonomy_term_count_nodes($tid, $type = 0) {
  static
$count;
 
  if (isset(
$count[$type][$tid])) {
    return
$count[$type][$tid];
  }
 
 
$query = db_select('taxonomy_index', 't');
 
$query->condition('tid', $tid, '=');
 
$query->addExpression('COUNT(*)', 'count_nodes');

 
// Restrict query by Content Type
 
if (!empty($type)) {
   
$query->join('node', 'n', 't.nid = n.nid');
   
$query->condition('type', $type, '=');
  }

 
$count[$type][$tid] = $query->execute()->fetchField();
 
  return
$count[$type][$tid];
}
?>

Login or register to post comments