1

I have the following iteration:

  foreach($category as $cat) {
              insert_term_if_not_exists($cat, 'tags');
              $term_tags = taxonomy_get_term_by_name($cat);
              $tid_tags = key($term_tags);
              $lang_tags = field_language('node', $node, 'field_tags');
              $node->field_tags[$lang_tags][0]['tid'] = $tid_tags;
            }
          }
       }
  node_save($node);

which relies on the following function to create non-existent taxonomy terms:

function insert_term_if_not_exists($term_name, $vocabulary_name) { 
  $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  $matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);
    if(empty($matched_terms)) {
      $term = new stdClass();
      $term->vid = $vocabulary->vid;
      $term->name = $term_name;
      taxonomy_term_save($term);
    } else {
      $term = array_shift($matched_terms);
    }
return $term;
}

This couple pieces of code work great to create new taxonomy terms (taken from $category array) and to associate a node with the last taxonomy term. And I need to add all of the taxonomy terms which went through iteration above to the node.

Looking everywhere to find proper instructions to add multiple taxonomy terms to a single node programmatically without much success. Hope someone here can point me to the right direction, thanks!

4

Finally I have a working code:

insert_term_if_not_exists($cat, 'tags');
              $term_tags = taxonomy_get_term_by_name($cat);
              $tid_tags = key($term_tags);
              array_push($tids, $tid_tags);
              $lang_tags = field_language('node', $node, 'field_tags');
            }
          }
          foreach ($tids as $index => $tid) { $node->field_tags[$lang_tags][$index]['tid'] = $tid; }

       }

All the credit goes to user Albright in IRC channel #drupal at http://webchat.freenode.net who pointed out to me that I needed to collect the tids in an array, then add a second loop which loops through that array and adds the tids one at a time to field_tags.

| 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.