Aug 28, 2017 in Drupal 8, Snippets

I've had some difficulties loading a list of translated terms. More in particular I didn't want to show the untranslated terms, but ONLY the ones that were already translated in the current language. The following snippet did the work:

$vocabulary = 'MY_VOCABULARY_NAME';
$language =  \Drupal::languageManager()->getCurrentLanguage()->getId();
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('vid', $vocabulary);
$query->sort('weight');
$tids = $query->execute();
$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
$termList = array();

foreach($terms as $term) {
    if($term->hasTranslation($language)){
        $tid = $term->id();
        $translated_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $language);
        $termList[$tid] = $translated_term->getName();
    }
}

// To print a list of translated terms. 
foreach($termList as $tid => $name) {
     print $name;
}

To link the tags to its term page, see https://drupal.stackexchange.com/a/243160/71941