Skip to content

Instantly share code, notes, and snippets.

@opi
Created December 6, 2011 10:39
Show Gist options
  • Select an option

  • Save opi/1437730 to your computer and use it in GitHub Desktop.

Select an option

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

opi commented Dec 6, 2011

Copy link
Copy Markdown
Author

@martinov

Copy link
Copy Markdown

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
Copy Markdown

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