Count how many nodes have a tid (taxonomy term id) in Drupal

Count how many nodes have a tid (taxonomy term id) in Drupal

If you need to get a count of how many nodes have a specific tid, there are a few ways of attacking the problem. One is by using views which I find overkill for this situation. You could use EntityFieldQuery which is a good option. But for this demo, I’m going to use a simple and basic db_select. You could also use db_query (which is faster) but I have a conditional statement and db_select makes that much cleaner to handle.

function mymodule_count_nodes_with_tid($tid, $type = NULL) {
  $query = db_select('taxonomy_index', 't');
  $query->condition('tid', $tid, '=');
  $query->addExpression('COUNT(*)', 'count_nodes');
  if (!empty($type)) { // optional - if looking for specific node type
    $query->join('node', 'n', 't.nid = n.nid');
    $query->condition('type', $type, '=');
  }
  return $query->execute()->fetchField();
}

If calling this multiple times, I would highly recommend using some form of caching such as cache_set/cache_get.

Comments are closed.