You are here

function hreflang_hierarchy_html_head_alter in Language Hierarchy 7

Implements hook_html_head_alter().

File

modules/hreflang_hierarchy/hreflang_hierarchy.module, line 6

Code

function hreflang_hierarchy_html_head_alter(&$head_elements) {
  $current_path = current_path();
  if (path_is_admin($current_path)) {
    return;
  }

  // Get path and translations
  $path = $_GET['q'];

  // Add hreflang="x-default" for front page.
  if (drupal_is_front_page()) {
    $path = '<front>';
    $element = array(
      '#tag' => 'link',
      '#attributes' => array(
        'href' => url($path),
        'rel' => 'alternate',
        'hreflang' => 'x-default',
      ),
      '#type' => 'html_tag',
    );
    $head_elements['hreflang:x-default'] = $element;
  }
  $translations = hreflang_hierarchy_get_links($path);

  // Get disabled languages
  $languages = language_list('enabled');

  // Other link types like panels pages or views.
  if (empty($translations)) {
    $translations = array();
    foreach ($languages[1] as $language) {
      $alias = drupal_get_path_alias($path, $language->language);
      $translations[$language->language] = array(
        'href' => $alias,
      );
    }
  }

  // Get alternate urls if we've got translations.
  if ($translations) {
    foreach ($translations as $langcode => $translation) {
      if (!empty($languages[1][$langcode]->hidden)) {
        continue;
      }
      $attributes = array(
        'href' => url($translation['href'], $translation + array(
          'language' => $languages[1][$langcode],
        )),
        'rel' => 'alternate',
        'hreflang' => $langcode,
      );

      // Build the hreflang element.
      $element = array(
        '#tag' => 'link',
        '#attributes' => $attributes,
        '#type' => 'html_tag',
      );
      $key = 'hreflang:' . $langcode . '/' . $translation['href'];
      $head_elements[$key] = $element;
    }
  }
}