0

I am checking if a taxonomy term has children using taxonomy_get_children and I wonder if this is the most efficient way of doing it. Since the function returns all the term objects, I believe it is not very efficient.

2

As arpitr says taxonomy_get_children() loads the child terms, so you are better of with a fork of this function.

I wanted to know whether a term a) is connected to any nodes and b) has any child terms.

/**
 * Helper function to check whether a term has no child terms and is not
 * connected to any node.
 *
 * @see taxonomy_get_children()
 */
function YOURMODULE_is_term_empty($tid, $vid) {
  $children = &drupal_static(__FUNCTION__, array());

  // Is term connected to node?
  if (!isset($children[$tid])) {
    // Get id's of connected nodes. Make query lighter by using no pager,
    // setting limit to 1 and sending an empty array with fields to order on.
    $node_ids = taxonomy_select_nodes($tid, FALSE, 1, array());

    if (!empty($node_ids)) {
      $children[$tid] = false;
    }
  }

  // Does term have child terms?
  if (!isset($children[$tid])) {
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
    $query->addField('t', 'tid');
    $query->condition('h.parent', $tid);
    $query->condition('t.vid', $vid);
    $query->addTag('term_access');
    $query_result = $query->execute()->fetchCol();

    $children[$tid] = empty($query_result);
  }

  return $children[$tid];
}

NB: I did not make this work recursively.

|improve this answer|||||
0

Yes the reason it returns terms object is because of

Check function definition here

$children[$tid] = taxonomy_term_load_multiple($tids);

If you think copy the function to a custom module rename it and return tids instead of loading terms and return the objects.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.