1

I have a term ID and I want to programmatically get the translated term name (via Entity Translation and the Title module) for the logged-in user's language. How can I do this?

This similar question asks about how to get the translated name programmatically when using i18n taxonomy translation (the other major approach besides Entity Translation).

1

The proper way to do this without circumventing the core API would be:

$tid = 322; // put here your term id
$term = taxonomy_term_load($tid);
$langcode = $GLOBALS['user']->language;
$translated_term = $term->name_field[$langcode][0]['value'];    
0

I resolved using this module that extends EntityFieldQuery

After installing it, you are able to extend EntityFieldQuery in the following way:

global $language;

$langcode = $language->language; // current site language
$tid = 322; // put here your term id

$query = new EntityFieldQueryExtraFields();
$query->entityCondition('entity_type', 'taxonomy_term')
      ->entityCondition('bundle', 'your_vocabulary_machine_name')
      ->entityCondition('entity_id', $tid, '=')
      ->addExtraField('name_field', 'value', 'value')
      ->fieldLanguageCondition('name_field', $langcode, '=');

$results = $query->execute();

if (isset($results['taxonomy_term'])) {
  $translated_term = $results['taxonomy_term'][$tid]->extraFields->name_field_value;
  // do what you want with $translated_term
}

Hope this help.

MXT

0

@plach's answer should technically work, but it has two problems:

  1. It unnecessarily handles the language.
  2. It's using an unsafe value, which is a security risk.

I recommend to instead use field_get_items() along with the safe value.

$term = taxonomy_term_load($tid);
$titles = field_get_items('taxonomy_term', $term, 'name_field');
if (!is_array($titles) || !isset($titles[0]) || !isset($titles[0]['safe_value'])) {
  $term_translated = 'Invalid or untranslated taxonomy term / tag!';
}
$term_translated = $titles[0]['safe_value'];

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.