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

Jun
2020
26
You can add this to your class or Controller etc. It always return the taxonomy term id if yound
<?php
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 <-- integer
     
return $term;
  }
?>
Tags: 
Cats: 
this is an arrow pointing back to the top of the page