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
Comments6
Running Check in Drush
I ran the check in Drush, but the first line throws "\Drupal::$container is not initialized yet".
What am I missing?
How do i use this code
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.
Create a custom module
For that you must create a custom module. Here a guide to create a custom module. You can also do in your template.php but it's not recommended.
Run drush php-script
Just create a php file inside your drupal installation and run "drush php-script your_file.php"
Insert custom field programatically
Hi,
how to insert custom field value to taxonomy to newly created taxonomy.
deprecated message
Using Term::create() as shown above generates the error,