Use custom language code (URL, lang and hreflang attribute)

Here, we explain how to change the default language code. This is useful if you don't like the default 2 letters code of Weglot in the URL and want to change it into another language code.

Example: Changing "tw" to "zh-HK"

In this post, we show for example how to change language code tw (Traditional Chinese) to zh-HK (Hong Kong Chinese).

<!-- HTML output by default (Traditional Chinese) -->
<html lang="tw">
<head>
<link rel="alternate" hreflang="en" href="https://mysite.com/"/>
<link rel="alternate" hreflang="tw" href="https://mysite.com/tw/"/>
</head>
<body>
<!-- ... -->
</body>
</html>
<!-- HTML output with custom language code (Hong Kong Chinese) -->
<html lang="zh-HK">
<head>
<link rel="alternate" hreflang="en" href="https://mysite.com/"/>
<link rel="alternate" hreflang="zh-HK" href="https://mysite.com/zh-HK/"/>
</head>
<body>
<!-- ... -->
</body>
</html>

Hook for customize language code

This hook must be load before your theme. This is why you can not use it in your functions.php. To use it, you can follow one of the 2 method below.

// Use zh-HK (Hong Kong Chinese) instead tw (Traditional Chinese)
add_filter( 'weglot_language_code_replace', 'custom_weglot_language_code_replace' );
function custom_weglot_language_code_replace( $replacements ) {
$replacements['tw'] = 'zh-HK';
return $replacements;
}

Method 1: Use plugin Code Snippets

  1. Add and activate Code Snippets plugin on your WordPress: https://wordpress.org/plugins/code-snippets/

  2. In your WordPress back office, go to Snippets -> Add new

  3. Add a title (example: Weglot - Custom language code)

  4. Add the following code into the code input. Don't copy <?php cause it's already added by the plugin.

  5. Save changes

Method 2: Create a MU-PLUGIN

  1. Create a new file : /wp-content/mu-plugins/weglot-language-code-replace.php

  2. Add the following code into the new file and save it.