Drupal - Programmatically create a term?

You know that you want something from taxonomy module so first you need to look in Drupal\taxonomy\Entity -- or the corresponding directory -- you will find the Term class there. Now look at the annotation, it says @ContentEntityType and in there:

*   entity_keys = {
*     "id" = "tid",
*     "bundle" = "vid",
*     "label" = "name",
*     "uuid" = "uuid"
*   },

So, what you want is

$term = Term::create([
  'name' => 'test', 
  'vid' => 'client',
])->save();

because the label entity key is name and the bundle entity key is vid. I added a ->save() call as well as I presume you wanted to save it too.


At this time you should add term in little bit another way (in compare with this answer) First of all in your file begin you should write

use Drupal\taxonomy\Entity\Term;

Because Term class listed in Drupal\taxonomy\Entity. And you don't need to pass taxonomy_term parametr to

Term::create

because only one parametr is needed (array with values) (below listed code for this method in taxonomy module)

public function create(array $values = array()) {
  // Save new terms with no parents by default.
  if (empty($values['parent'])) {
    $values['parent'] = array(0);
  }
  $entity = parent::create($values);
  return $entity;
}

So the final example is

use Drupal\taxonomy\Entity\Term;
$categories_vocabulary = 'blog_categories'; // Vocabulary machine name
$categories = ['test 1', 'test 2', 'test 3', 'test 4']; // List of test terms
foreach ($categories as $category) {
  $term = Term::create(array(
    'parent' => array(),
    'name' => $category,
    'vid' => $categories_vocabulary,
  ))->save();
}

Term::create([
 'name' => 'Lama',
 'vid' => $vocabulary_id,
]);

The other answers use entity_create(), which works, but is not quite as nice as the OOP approach.