10

I'm looking for a working method to get the translated term name by tid.

The following code returns the original term name but not the translation.

global $language;

$lang_name = $language->language; // en

$term_id = 788;

$term = i18n_taxonomy_term_get_translation($term_id, $lang_name);

Example of a translated Taxonomy Term (German to English)

Most examples provided in "how to get the translated taxonomy term programmatically?" seem not work for Drupal 7.

3
  • i think the code should work but the first parameter should be a term object and not a term id...
    – lenni
    Jul 11, 2013 at 12:37
  • @lenni Unfortunately it does not to work. Drupal returns the same object back.
    – mate64
    Jul 11, 2013 at 13:35
  • Here's how to do it with Drupal 8.
    – Hugo
    Oct 5, 2017 at 7:57

5 Answers 5

17

I managed to make it work! This is my code

$tree = taxonomy_get_tree(9); // Your taxonomy id

foreach ($tree as $term) {
  if (module_exists('i18n_taxonomy')) { //To not break your site if module is not installed
    $term = i18n_taxonomy_localize_terms($term); // The important part!
  }
  print l($term->name, 'taxonomy/term/' . $term->tid); //print the terms
}

That sould do it! Diadeuf!

12

I had the same problem with localized taxonomy term translations. If you have your "Multilingual options" translation mode set to "Localize", then it's pretty straightforward.

Let's say your term id is 788 like the OP's, then just do something along these lines:

  $i18n_object = i18n_get_object('taxonomy_term', 788);
  $target_langcode = 'de';
  $translated_term = $i18n_object->localize($target_langcode);
2
  • 1
    It worked for me!, weird that the function i18n_taxonomy_localize_terms didn't. thx
    – GwenM
    Dec 19, 2014 at 14:07
  • Worked perfect. Like @Namari function i18n_taxonomy_localize_terms didn't seem to do its job.
    – jan
    Jan 27, 2015 at 14:13
12

You should use the i18n_taxonomy_localize_terms() function. This is the working code for me:

$tid = 10;
$term = taxonomy_term_load($tid);
$translated_term = i18n_taxonomy_localize_terms($term);
print $translated_term->name;
1

Knibals code shows how to translate a full vocabulary tree. This code snippet shows how to translate one specific term.

$term = taxonomy_term_load($tid);
$translated_term = i18n_taxonomy_term_get_translation($term, $langcode);

This question was already answered here: how to get the translated taxonomy term programmatically?

0

If you want to use it as Function..

function _get_term_name_translate($tid) {
  $term = i18n_taxonomy_localize_terms(taxonomy_term_load($tid));
  return $term->name;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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