Create taxonomy term programmatically on Drupal 8 | Drupal 8

Create taxonomy term programmatically on Drupal 8

Submitted by editor on Wed, 12/02/2015 - 11:32
Question

How to add a taxonomy term programmatically in drupal 8 ?

Example : Create a terom of the vocabulary 'test_vocabulary'

//Minimum
$term = \Drupal\taxonomy\Entity\Term::create([
          'vid' => 'test_vocabulary',
          'name' => 'My tag',
    ]);
$term->save();

//With options
$term = \Drupal\taxonomy\Entity\Term::create([
          'vid' => 'test_vocabulary',
          'langcode' => 'en',
          'name' => 'My tag',
          'description' => [
            'value' => '<p>My description.</p>',
            'format' => 'full_html',
          ],
          'weight' => -1,
          'parent' => array(0),
    ]);
 $term->save();

//Add term with a custom field. Example : 'field_url'
$term = Term::create([
            'vid' => 'test_vocabulary',
            'name' => 'The Name',
            'field_url' => [$url],
      ]);
$term->save();

//Check Taxonomy name exist
    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "test_vocabulary");
    $query->condition('name', "My tag");
    $tids = $query->execute();

Thanks to : https://gist.github.com/facine/35bb291811c146b6fc9e

Comments

Juston (not verified)

Thu, 01/05/2017 - 00:55

I ran the check in Drush, but the first line throws "\Drupal::$container is not initialized yet".

What am I missing?

Mohsin (not verified)

Thu, 03/02/2017 - 10:33

Hello there,

Can you please guide where to put this code so that it can be executed. I do not know I have to create a separate PHP file or I need to use in theme_name.them file or I have to create a custom module to use this.

Please guide me.

Thanks in advance.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.