0

I am using the following code.

$language =  \Drupal::languageManager()->getCurrentLanguage()->getId();
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('category', 0, 1);

How can I change it so it load the taxonomy terms basing on $language?

3

Use EntityRepositoryInterface::getTranslationFromContext:

$terms_translated = [];
foreach ($terms as $key => $term) {
  $terms_translated[$key] = \Drupal::service('entity.repository')
    ->getTranslationFromContext($term, $language);
}

BTW, you don't need to provide a language code, because the current content language is the default value for the second parameter in getTranslationFromContext() and in a standard multilanguage site this is equal to the current language.

  • Thanks @4k4 for answer. I have updated code. Getting error can you please help with that? – Mike Jan 3 '18 at 2:28
  • You need a 4th parameter to load the terms: loadTree('category', 0, 1, TRUE). (don't edit the answer into the question, future readers don't see the original question) – 4k4 Jan 3 '18 at 7:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.