Skip to content

Instantly share code, notes, and snippets.

@opi

opi/gist:1437730

Created Dec 6, 2011
Embed
What would you like to do?
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

This comment has been minimized.

@martinov

This comment has been minimized.

Copy link

@martinov martinov commented Aug 17, 2012

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

This comment has been minimized.

Copy link

@martinov martinov commented Aug 17, 2012

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