We’ve covered how to programmatically create a vocabulary in a previous post. Here’s how to insert a term into our vocabulary, checking to make sure that the term doesn’t already exist.
Inserting the Term
/**
* Insert a term into a vocabulary, if the term doesn't already exist.
* @param $term_name Name of the term to insert
* @param $vocabulary_name Machine name of the vocabulary
* @return Term object representing the term
*/
function insert_term_if_not_exists($term_name, $vocabulary_name) {
// Get the vocabulary object, using the machine name.
$vocabulary = taxonomy_vocabulary_machine_name_load('vocabulary_name');
// Get the list of matched terms of our term name.
$matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);
// Add the term if it doesn't already exist.
if(empty($matched_terms)) {
// There are no matched terms, so add the term.
$term = new stdClass();
$term->vid = $vocabulary->vid;
$term->name = $term_name;
taxonomy_term_save($term);
} else {
// The term already exists in the vocabulary.
// Return the first object in the list of matched terms.
$term = array_shift($matched_terms);
}
// Return the term object.
return $term;
}
Assigning the Term to a Node
Now that we have the term object (if it didn’t exist, it was created and if it already existed the term object was returned), we can assign the term to a node.
// Try inserting the term.
$term = insert_term_if_not_exists('My New Term', 'my_vocabulary_machine_name');
// Assign the term to the node, assuming we have the $node object.
// The field_name is the field name of your term reference field.
$node->field_name[LANGUAGE_NONE][] = $term;