You are here

hreflang.module in Hreflang 7

Same filename and directory in other branches
  1. 8 hreflang.module

Adds hreflang link elements to the header of each page.

File

hreflang.module
View source
<?php

/**
 * @file
 * Adds hreflang link elements to the header of each page.
 */

/**
 * Implements hook_page_build().
 */
function hreflang_page_build(&$page) {

  // Return early if site is monolingual.
  if (!drupal_multilingual()) {
    return;
  }

  // No need to add hreflang tags for 404/403 pages.
  $status = drupal_get_http_header('status');
  if ($status == '404 Not Found' || $status == '403 Forbidden') {
    return;
  }
  $path = drupal_is_front_page() ? '' : $_GET['q'];
  $links = language_negotiation_get_switch_links(LANGUAGE_TYPE_INTERFACE, $path);
  if (empty($links->links)) {
    return;
  }
  foreach ($links->links as $link) {

    // Content translation module may unset the href attribute.
    if (!isset($link['href']) || !isset($link['attributes']['hreflang'])) {
      continue;
    }
    $link['absolute'] = TRUE;
    if (!isset($link['query'])) {
      $link['query'] = array();
    }
    $link['query'] += drupal_get_query_parameters();

    // Remove superfluous page = (float) 0 added by comment_permalink().
    if (isset($link['query']['page']) && $link['query']['page'] === 0.0) {
      unset($link['query']['page']);
    }
    $attributes = array(
      'href' => url($link['href'], $link),
      'rel' => 'alternate',
      'hreflang' => $link['attributes']['hreflang'],
    );
    drupal_add_html_head_link($attributes);
  }
}

/**
 * Implements hook_language_switch_links_alter().
 */
function hreflang_language_switch_links_alter(array &$links, $type, $path) {
  foreach ($links as $langcode => &$link) {
    $link['attributes']['hreflang'] = $langcode;
  }
}