Here’s a Drupal 8/9/+ answer, designed as a static PHP class method:
You can add this method in any class and can call using self operator.
Example: self::getTidByName(“term-name”, “vocabulary machine name”);
This will return term id if given term name matches, else it will return 0 if not matched.
/**
* Utility: find term by name and vid.
*
* @param string $name
* Term name.
* @param string $vid
* Term vid.
*
* @return int
* Term id, or 0 if none.
*/
public static function getTidByName($name = NULL, $vid = NULL) {
if (empty($name) || empty($vid)) {
return 0;
}
$properties = [
'name' => $name,
'vid' => $vid,
];
$terms = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term')->loadByProperties($properties);
$term = reset($terms);
return !empty($term) ? $term->id() : 0;
}
With this function, you can create new term if this functions returns 0, Like below
$term =Term::create([ 'name' =>$term_name, 'vid' => $vid, ])->save();