Information for: DEVELOPERS   PARTNERS

Create terms programmatically

Lesson Goal

This task demonstrates how to create taxonomy terms in code. Drupal has a method specifically for this action.

Implementation Method

Drupal Version Method
Drupal 7 Use taxonomy_term_save() to create and then save the term to the specified vocabulary
Drupal 8 Use \DrupaltaxonomyEntityTerm to create and then save the term into the specified vocabulary

Drupal 7 method

Add the following code to the lotus.module file:

function lotus_term_create() {
 $new_term = new stdClass();
 $new_term->name = 'Your term name';

 // Make sure you know the vocabulary ID.
 // Look at lotus_get_vocabulary_id_by_name()
 // for an example.
 $vid = lotus_get_vocabulary_id_by_name('Vocab name');
 $new_term->vid = $vid;

 function lotus_get_vocabulary_id_by_name($vocabulary_name) {
 $vocabs = taxonomy_get_vocabularies(NULL);
 foreach ($vocabs as $vocab_object) {
     if ($vocab_object->name == $vocabulary_name) {

     $vid = $vocab_object->vid;
     return $vid;
 return NULL;

Drupal 8 method

Add the following code inside a function where you want to create new terms:

$new_term = \Drupal\taxonomy\Entity\Term::create([
    'vid' => 'example_vocabulary_machine_name',
    'name' => 'Example term name',