Get correct link to translated version of given node

I am using this snippet on a multilingual enabled site to get the correct translated link of a given node that is hardcoded in a block.

$nodepath is the path to the node of which you want to have a link to the translated version in the current language.



$nodepath = "node/106";

$languagepaths = translation_path_get_translations($nodepath);
$currentlanguage = i18n_get_lang();
$path = $languagepaths[$currentlanguage];

if (preg_match('/^node/',$path)) {
  if ( $currentlanguage == "en" ) {
    $path = drupal_get_path_alias($path, $currentlanguage);
  } else {
    $path = $currentlanguage ."/". drupal_get_path_alias($path, $currentlanguage);
  }
} else {
    $path = $nodepath;
}

echo '<a href="/'. $path. '">Link</a>';

Comments

sandu.camerzan’s picture

I use this helper function to generate a group of language switcher links for all enabled languages for a miltilingual site.
It handles both node translations and the translation of multilingual vocabularies with translatable terms.

function _language_switcher() {
  global $language;
  $languages = language_list('enabled');
  $path = drupal_is_front_page() ? '<front>' : $_GET['q'];

  //handle node translations
  if(arg(0) == 'node' && arg(1)>0) {
    $node_path = 'node/'. arg(1);
    $language_paths = translation_path_get_translations($node_path);
  }

  //handle term translations
  if(arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2)>0) {
    $term = taxonomy_get_term(arg(2));
    $language_terms = i18ntaxonomy_term_get_translations(array('tid' => arg(2)));
  }

  if (count($languages[1])>1) {
    $lang_switches = array();
    foreach ($languages[1] as $lang) {
      if($lang->language != $language->language) {
        $modifier = $lang->native;
        //we are translating a node. Check if not neutral or missing translations.
        if($language_paths && !empty($language_paths))
          $path = $language_paths[$lang->language];
        //we are translating a term.
        if($term) {
          $path = 'taxonomy/term/'. $language_terms[$lang->language]->tid;
        }
        $lang_switches[] = l($modifier, $path, array('language' => $lang));
      }
    }
    return implode('<br />', $lang_switches);
  }
}
ytsurk’s picture

was wrong --

aha - interesting ..

candelas’s picture

this is good for d6. any for d7? thanks

//trying to answer one question for each one that i make.
//this way, drupal will be more friendly and strong