WPML: hide or rewrite language URLs in language switcher and hreflang tags

Amend the list of languages used by WPML’s language switcher, icl_get_languages() function and hreflang tags


There are a few scenarios in which you may want to hide a particular language from your WordPress site using WPML for multi-language content. You may be in the progress of populating a new language on the site and not yet be ready for it to be referenced in the language switcher or within the hreflang tags that are automatically added to the header of each page for search engine discovery.

The following snippet will allow you to modify or remove language URLs from the WPML language switcher as well as the icl_get_languages() function which you may be using to build your own language switcher. It also affects the hreflang tags at the same time, allowing you to modify the list of languages that are referenced within the site code with one easy filter.

As you’ll see below, we add this filter to icl_ls_languages and wpml_head_langs. As their names suggest, the first filter is responsible for the icl_get_languages() function that can be used to manually retrieve a list of active languages on a WPML site while wpml_head_langs is the function that builds the hreflang tags in the site header.

The following code snippet modifies the $languages variable which contains an array of active languages, before returning the modified array. In the example below, we show how it is possible to unset a language (AU in this case) or modify URLs using str_replace() to change www. links to point to a staging. subdomain instead. This can be useful if you need to point a specific language to a different staging address or perhaps are working with a headless WordPress integration where the CMS is installed on a different URL to the frontend.


// Amend the list of WPML languages

function bb_wpml_url_fix( $languages ) {
 
  unset($languages['au']);

  $languages['us']['url'] = str_replace('www.', 'staging.', $languages['us']['url']);
  $languages['en']['url'] = str_replace('www.', 'staging.', $languages['en']['url']);

  return $languages;

}
add_filter( 'icl_ls_languages', 'bb_wpml_url_fix');
add_filter( 'wpml_head_langs', 'bb_wpml_url_fix');

A lightweight, intuitive WordPress theme to enable flexible developement.

  • Lighting-fast installer
  • Intuitive SASS structure
  • Bloat-free

Build with Barebones