I'm trying to develop an script to upgrade nodes with a term reference.

But my source has 3 columns (copy to an in a db table) to the term tree, example:

fieldnames: ref1, ref2, ref3 fields: CAR -> REDCAR -> DARKRED

I can't use term name because it has is duplicates on the tree. Example: fields: CAR -> REDCAR -> DARKRED fields: BIKE -> REDBIKE -> DARKRED

How to get the right TID and verifying the tree with my DB table?

  • You might find some useful code in this module
    – Darvanen
    Feb 22, 2015 at 1:46
  • Thank's, I checked the module and doing a loop with an array_reverse might do the job.
    – sainf
    Feb 23, 2015 at 9:50

1 Answer 1


Darvanen, shs code didn't help, the module has always the correct tid, but I have to find it in a tree.

So I made my own function. (note I'm not a php pro)

function getcorrecttid() {

$nodes = db_query('SELECT cat1, cat2, cat3 FROM {TABLE});

// record loop
foreach($nodes as $node) {

// get TID with the last column
$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('name', $node->cat3)
  ->propertyCondition('vid', 3)

// check if has more than one
if (count($result['taxonomy_term']) > 1 ) {
  $tids = array();
  $tids = $result['taxonomy_term'];
  $i = 0;
  foreach ($tids as $t) {
    $Keys = array_keys($tids);

    $parent = taxonomy_get_parents($Keys[$i]);
    $pKeys = array_keys($parent);
    $c = 0;
    foreach ($pKeys as $b) {
      $pnum = array_keys($parent);
      if ($parent[$pnum[$c]]->name == $node->cat2) {
        $root = taxonomy_get_parents($pKeys[$c]);
        $rKeys = array_keys($root);
        $a = 0;
        foreach ($rKeys as $z) {
          // found a correct TID after a lot of loops, (caution this is a heavy, heavy search.....)
          $mytid = $Keys[$i];
} else {
  $mytid = array_shift($result['taxonomy_term'])->tid;
  // Found no multi parents...

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.