function hreflang_page_attachments in Hreflang 8
Implements hook_page_attachments().
File
- ./
hreflang.module, line 28 - Adds hreflang link elements to the header of each page.
Code
function hreflang_page_attachments(array &$page) {
// No need to add hreflang tags for 404/403 pages.
if (\Drupal::request()->attributes
->has('exception')) {
return;
}
$language_manager = \Drupal::getContainer()
->get('language_manager');
if (!$language_manager
->isMultilingual()) {
return;
}
$route = \Drupal::service('path.matcher')
->isFrontPage() ? '<front>' : '<current>';
$links = $language_manager
->getLanguageSwitchLinks(LanguageInterface::TYPE_INTERFACE, Url::fromRoute($route));
if (empty($links->links)) {
return;
}
foreach ($links->links as $langcode => $link) {
if (!isset($link['query'])) {
$link['query'] = [];
}
$link['query'] += \Drupal::request()->query
->all();
if (isset($link['url'])) {
$link['url']
->setOptions($link);
$link['url']
->setAbsolute();
$page['#attached']['html_head_link'][] = [
[
'rel' => 'alternate',
'hreflang' => $langcode,
'href' => $link['url']
->toString(),
],
TRUE,
];
}
}
}