Skip to main content

Checking if a term exists (by name) and create one if not found with Drupal 8

use Drupal\taxonomy\Entity\Term;
//Vid in drupal 8 is the vocabulary machine name e.g news_categories and not an integer id as in drupal 7
private function manage_term($term_name,$vid){
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties(['name' => $term_name, 'vid' => $vid]); 
$term = reset($term); 
if ($term){ return $term->id(); } 
$term =Term::create([ 'name' =>$term_name, 'vid' => $vid, ])->save(); 
//Returns $term id value e.g 2,3,577 
return $term; 

You can add this to your class or Controller etc. It always return the taxonomy term id