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.

Ben (not verified)

Tue, 08/07/2018 - 22:30

Using Term::create() as shown above generates the error,

PHP Deprecated:  Automatically creating the first item for computed fields is deprecated in Drupal 8.5.x and will be removed before Drupal 9.0.0. Use \Drupal\Core\TypedData\ComputedItemListTrait instead.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.