<?php
/**
* @param tid
* Term ID
* @param child_count
* TRUE - Also count all nodes in child terms (if they exists) - Default
* FALSE - Count only nodes related to Term ID
* @param node_type
* Count only nodes of one type (string).
*/
function term_count_nodes($tid, $child_count = TRUE, $node_type = NULL) {
$tids = array($tid);
if ($child_count) {
$tids = array_merge($tids, term_get_children_ids($tid));
}
global $language;
$langs = array($language->language);
$langs[] = 'und';
$query = db_select('taxonomy_index', 't');
$query->condition('tid', $tids, 'IN');
$query->join('node', 'n', 't.nid = n.nid');
$query->condition('n.status', 1, '=');
$query->condition('n.language', $langs, 'IN');
if ($node_type) {
$query->condition('n.type', $node_type, '=');
}
$count = $query->countQuery()->execute()->fetchField();
return $count;
}
/**
* Retrieve ids of term children .
*
* @param $tid
* The term's ID.
* @param $tids
* An array where ids of term children will be added
*/
function term_get_children_ids($tid) {
$children = taxonomy_get_children($tid);
$tids=array();
if (!empty($children)) {
foreach($children as $child) {
$tids[] = $child->tid;
$tids = array_merge($tids, term_get_children_ids($child->tid));
}
}
return $tids;
}