You are here

function hreflang_page_build in Hreflang 7

Implements hook_page_build().

File

./hreflang.module, line 11
Adds hreflang link elements to the header of each page.

Code

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);
  }
}