Create terms programmatically

Tutorial Goal

Lesson Goal:

Implementation Method




taxonomy_term_save() to create and save the term to the specified vocabulary.

\Drupal\taxonomy\Entity\Term to create then save the term into the specified vocabulary.

D7 Code

Add the following in 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;

D8 Code

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

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


Gist Link


Contact supportStill need assistance? Contact Acquia Support