August 22, 2009

Drupal – create links to translated nodes

Filed under: Tips — Tags: , , , — Webopius @ 1:37 pm

When you are using Drupal’s internationalisation module, you will often reach the point in your page and node templates where you need to create a dynamic link to the correct content item depending on the site’s current language. The title of the link may also change to represent the language choice.

For example, /node/10 might be the English language version of a page, while /node/231 might be the French translation of the same content. In your template, you’ll need to dynamically generate a link to the right node AND the correct title text of the link depending on whether your user is viewing the original site (e.g. or a translated version (www/

Here’s a quick solution, in your theme’s template.php file, create the following function:

/* Given a node id, find the current language and return a link to the node's translation (if any) */

function _translation_nodelink($nid) {
   global $language;
   // Look for a translated version of this node in the current site selected language
   $result = db_query("SELECT n2.nid, n2.title FROM {node} n1, {node} n2 WHERE n1.tnid = n2.tnid and n1.nid = %d and n2.language = '%s'", $nid, $language->language);
   $node = db_fetch_object($result);
   if ($node) {
      print l($node->title,"node/".$node->nid);
      // No translation available, return the node's own original language title
      $node = node_load($nid);
      print l($node->title,"node/".$nid);

Now, in your theme templates, wherever you need to generate the correct link to a node’s translated content depending on the language being used by the site, you simply include the following:

<?php print _translation_nodelink($nodeid)?>

Where $nodeid should be the node id of the ‘base language’ node (e.g. the English version).

What will happen is if the user is viewing the site in another language, this function will detect the language being used and generate a link to the translated node (if one is available), otherwise, it will generate a link to the original non-translated node. The link title will also be translated if a title translation is available.

  • Tags