Skip to content

Instantly share code, notes, and snippets.

@leymannx
Created February 17, 2016 09:17
Show Gist options
  • Save leymannx/1395f785f55d761b1326 to your computer and use it in GitHub Desktop.
Save leymannx/1395f785f55d761b1326 to your computer and use it in GitHub Desktop.
Drupal 7 Snippet to create taxonomy term by name, if it doesn't exist yet and return the term object anyways.
/**
* Helper function to create a term by name, if it doesn't exist yet.
*
* @param $term_name string
* Human readable term name.
* @param $vocabulary_name string
* Vocabulary machine name.
* @param $weight integer.
* Term weight.
*
* @return object
*/
function _create_term($term_name, $vocabulary_name, $weight) {
$term = taxonomy_get_term_by_name($term_name, $vocabulary_name);
if (!empty($term)) {
return $term;
}
$vocab = taxonomy_vocabulary_machine_name_load($vocabulary_name);
$term = new stdClass();
$term->name = $term_name;
$term->vid = $vocab->vid;
$term->weight = $weight;
taxonomy_term_save($term);
return $term;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment