Not sure where to put this but I need this quite often so wrote a simple function that someone else might find helpful.

function taxonomy_get_children_all($tid, $vid = 0, $key = 'tid'){
	$c = taxonomy_get_children($tid, $vid, $key);
	foreach ($c as $t => $d){
		$result[$t] = $d;
		$below = taxonomy_get_children_all($t, $vid, $key);
		if (!empty($below)) {
			foreach ($below as $nt => $nd){
				$result[$nt] = $nd;
			}
		}
	}
	return $result;
}

Hope it's useful to someone.

Comments

agileadam’s picture

This was very helpful indeed! Thank you.

ssafiullah_h’s picture

it helped me as well.

SilviuChingaru’s picture

For a corect output after:

function taxonomy_get_children_all($tid, $vid = 0, $key = 'tid'){
	$c = taxonomy_get_children($tid, $vid, $key);

put this line:

$result = array();

the function should look like this now:

function taxonomy_get_children_all($tid, $vid = 0, $key = 'tid'){
	$c = taxonomy_get_children($tid, $vid, $key);
	$result = array();
	foreach ($c as $t => $d){
		$result[$t] = $d;
		$below = taxonomy_get_children_all($t, $vid, $key);
		if (!empty($below)) {
			foreach ($below as $nt => $nd){
				$result[$nt] = $nd;
			}
		}
	}
	return $result;
}

Thanks for this func!

--
Works at Magazinul Cu Scule .ro

rubymuse’s picture

function taxonomy_get_children_all($tid, $vid = 0, $key = 'tid'){
  $c = taxonomy_get_children($tid, $vid, $key);
  $result = array();
  foreach ($c as $t => $d){
    $result[$t] = $d;
    $below = taxonomy_get_children_all($t, $vid, $key);
    if (!empty($below)) {
      $result[$t]->children = array();
      foreach ($below as $nt => $nd){
        $result[$t]->children[$nt] = $nd;
      }
    }
  }
  return $result;
}
stef266’s picture

I know it's an old post, but please can someone tell me where to put this function? Thanks

WorldFallz’s picture

It needs to go in a custom module.

Chi’s picture

Simple function to get all child tids.

function taxonomy_get_child_tids_all($tid, $vid, $max_depth = 5) {
  $query = db_select('taxonomy_term_data', 't');

  $query->leftJoin('taxonomy_term_hierarchy', 'h1', 'h1.tid = t.tid');
  $or_condition = db_or()->condition('h1.parent', $tid);

  for ($level = 2; $level <= $max_depth; $level++) {
    $previous_level = $level - 1;
    $query->leftJoin('taxonomy_term_hierarchy', "h$level", "h$level.tid = h$previous_level.parent");
    $or_condition->condition("h$previous_level.parent", $tid);
  }

  $query->condition($or_condition);
  $query->addField('t', 'tid');
  $query->condition('t.vid', $vid);
  $query->addTag('term_access');

  return $query->execute()->fetchCol();
}

________________________
Override, don't change!

ibit’s picture

deleted

klidifia’s picture

taxonomy_get_tree($vid, $tid);

I think that is the way to go, you'll get all the children and children's children. Check out the function and note that there is a max_depth that can be set.