WPML change hreflang attribute value to x-default

Diving into WPML functions.

In WPML plugin ./classes/seo/ class-wpml-seo-headlangs.php file, we can find head_langs function, which is responsible for displaying <link> tag with hreflang attribute in <head>. Moreover inside this function, we can find that “wpml_hreflangs” filter hook is applied. In other words we can change hreflang attribute value before WPML displays it. For example below we will change default language code hreflang to “x-default”.

In order to switch our default language code to “x-default” we need to add additional “wpml_hreflangs” filter hook using add_filter function. This filter provide to us array with available languages. Before looping through an array, we must get our default language code. It can be done with WPML “wpml_default_language” filter. After receiving default language code, we must loop through languages array and find iteration where array key is equal to default language code. Furthermore, we set new “x-default” key in array and provide value, which is equal to “key” same to default language code. Additionally we unset key with default language code and return our modified array.

In short:

  1. Add “wpml_hreflangs” filter hook;
  2. Get default language code with apply_filters(‘wpml_default_language’, null);
  3. Loop through array provided by “wpml_hreflangs” filter;
  4. Find key which is equal to default language code;
  5. Set new “x-default” key and add value from key with default language code;
  6. Unset key which is equal to default language code;
  7. Return modified array;

Function to change hreflang to “x-default”.

function modify_hreflangs($langs){

  // Get default language code
  $default_lang = apply_filters('wpml_default_language', null);

  foreach ($langs as $key => $lang) {

    // If language code = default language code
    if ($key === $default_lang) {

      // Set x-default hreflang
      $langs['x-default'] = $lang;

      // Unset hreflang with default language code
      unset($langs[$key]);

    }

  }

  return $langs;

}

add_filter('wpml_hreflangs', 'modify_hreflangs');