Setting Drupal Free Tags Programmatically

Last modified: 
Sunday, March 29th, 2015

Overview

The following demonstrates a means to add taxonomy terms programmatically in Drupal 7 using a free tagging type of arrangement.

Problem

  1. In this scenario we are using an external script (not shown here) to add new nodes to a Drupal 7 website programmatically.

  2. We want to associate any number of terms in the vocabulary food to each node using a Term reference field having the machine name field_food.

  3. We want to be able to create new terms in the food vocabulary on the fly.

  4. We want all terms in the food vocabulary to be unique.

Solution

// This demonstrates how to get the vid by way of the
// vocabulary's machine name.
$vocab_machine_name = 'food';
$vocab = taxonomy_vocabulary_machine_name_load($vocab_machine_name);
// $vid = $vocab->vid;

// Add Taxonomy Terms Using Free Tagging

// These variables must be set, but you shouldn't 
// have to change aynthing in the foreach loop.
$node->language = LANGUAGE_NONE;
$field_name = 'field_food';
$vid = $vocab->vid;
$terms = array('apple', 'pear', 'avocodo', 'spinach');



foreach ($terms as $term) {
  $vterms = taxonomy_get_term_by_name($term);  
  // taxonomy_get_term_by_name() doesn't filter by vid, nor does it 
  // insure that a term name is unique in a given vocabulary. This means
  // we have to jump through some hoops. We only want unique term names, and
  // we want it to come from a specific vocabulary, so we're going to loop
  // through all the results and stop when we find a match.
  foreach ($vterms as $vterm) {
    if ($vterm->vid == $vid) {
      break;
    }
    unset($vterm);
  }
  // If this term doesn't yet exist, we must first create it 
  // so the tid can be referenced.  
  if (!$vterm) {
    $vterm = array(
      'vid' => $vid,
      'name' => $term
    );
    $vterm = (object) $vterm;
    taxonomy_term_save($vterm);
  }
  // Set the term.  
  $node->{$field_name}[$node->language][]['tid'] = $vterm->tid;
  unset($vterm);
}


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.