Skip to content

Instantly share code, notes, and snippets.

@chupzzz
Last active July 7, 2017 18:26
Show Gist options
  • Save chupzzz/4dee8647e1cbab2ce818e047374c5599 to your computer and use it in GitHub Desktop.
Save chupzzz/4dee8647e1cbab2ce818e047374c5599 to your computer and use it in GitHub Desktop.
Drupal 7: Get Taxonomy node count
<?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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment