Skip to content

Instantly share code, notes, and snippets.

@opi
Created December 6, 2011 10:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save opi/1437730 to your computer and use it in GitHub Desktop.
Save opi/1437730 to your computer and use it in GitHub Desktop.
HTML Link element with rel="alternate" for multilingual Drupal website
<?php
/**
* More info : http://www.google.com/support/webmasters/bin/answer.py?answer=189077&hl=en
*/
/**
* Implements hook_preprocess_page()
*/
function mymodule_preprocess_page(&$vars) {
global $language;
// Get enabled languages, and remove current
$languages = array_pop(language_list('enabled'));
unset($languages[$language->language]);
// Get path
$path = drupal_is_front_page() ? '<front>' : $_GET['q'];
// Get urls
$links = array();
foreach($languages as $lang) {
$links[$lang->language] = array(
'href' => $path,
'language' => $lang,
'absolute' => TRUE,
);
}
drupal_alter('translation_link', $links, $path);
// Set head tags
foreach($links as $link) {
drupal_set_html_head('<link rel="alternate" hreflang="'. $link['language']->language .'" href="'. url($link['href'], $link) .'" />');
}
// Update head
$vars['head'] = drupal_get_html_head();
}
@opi
Copy link
Author

opi commented Dec 6, 2011

@martinov
Copy link

In my case I had to use array_shift() instead of array_pop() at the line where language_list('enabled') is called, otherwise I get the disabled languages ;-)

@martinov
Copy link

On a second thought, a better solution is to replace this line with the following two:

$languages = language_list('enabled');
$languages = $languages[1];

This will solve the issue no matter where the position of the enabled languages is in the array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment