Drupal – Redirect when Missing Node Translation

The following code help displaying a warning message and redirect to the site home page if a node translation does not exist. Create a custom module and implement the hook_init() method as follow.

custom.module

/**
 * Implementation of hook_init()
 *
 * Handle the case when the current language does not match content node language.
 * Reference: http://drupal.org/node/274761#comment-909800
 */
function custom_init() {
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    // if current language does not match content node language
    global $language;
    if (!empty($node->language) && $node->language != $language->language) {
      // lookup translations for current node
      $translations = translation_node_get_translations($node->tnid);
      // redirect if there's a translation in the currently active language
      if (isset($translations[$language->language])) {
        drupal_goto('node/' . $translations[$language->language]->nid);
        break;
      }
      // else display locale front_page and display "page not yet translated" message
      else {
        $url = referer_uri() ? referer_uri() : 'javascript:history.go(-1)';
        $msg = t('Sorry, the page %title is not available in @language. ' . '<a href="!url" title="Return to the previous page">Go Back!</a>',
          array('%title' => $node->title, '@language' => $language->native, '!url' => $url));
        drupal_set_message($msg, 'warning');
        drupal_goto(variable_get('site_frontpage', 'node'), null, null, 307);
        break;
      }
    }
  }
} 

 

Done =)

Reference: Handling missing translations

2 thoughts on “Drupal – Redirect when Missing Node Translation”

  1. I’ve made a module with this code. I’d like this module to redirect to the homepage of the selected language if the node has no translation and I think the module is supposed to do that… But when I switch from a node to another with the language switcher this doesn’t work…

    Maybe because I have node with clean urls?

    Like

    1. Hi Michel,

      it should work even you have enabled clean urls. so what did u get when u switch the language when viewing a node which does not have a corresponding translation?

      Kit

      Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.