This logic could be useful for migration, deploy hooks etc.
/**
* Helper function to get/create term by name and vid.
*
* @param string $vid
* Taxonomy vocabulary machine name.
* @param string $term_name
* Taxonomy term name.
*
* @return int
* Taxonomy term id.
*/
function _get_term_tid_by_name_and_vid(string $vid, string $term_name) {
$term_storage = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term');
// Trying to get existing term id.
$term_tid = $term_storage->getQuery()
->condition('vid', $vid)
->condition('name', $term_name)
->execute();
if ($term_tid) {
return reset($term_tid);
}
else {
// Creating a new term if it doesn't exist.
$new_term = $term_storage->create([
'vid' => $vid,
'name' => $term_name,
'status' => 1,
'uid' => 1,
]);
$new_term->save();
return $new_term->id();
}
}