Skip to main content
Le panier est vide

Customizing hreflang to Use Language Code Only

Overview

By default, Falang for WordPress generates hreflang attributes using the full locale code (for example fr-FR, en-US, es-ES).

In some cases, you may prefer to use only the language code (for example fr, en, es) in your hreflang tags — especially if your site does not target specific regional variations.

This guide explains how to modify your theme’s functions.php file to achieve that.

1 – Open your theme’s functions.php file

You can find it in your active theme folder, usually at:

/wp-content/themes/your-theme/functions.php

Open this file in your code editor or from the WordPress admin area under
Appearance → Theme File Editor → functions.php.

2 – Add the custom function

Copy and paste the following PHP code at the end of the functions.php file:

/**
 * Modify Falang hreflang array to use only the language code (e.g., 'fr' instead of 'fr-FR')
 */
function change_hreflang(array $hreflangs): array {
    $newHreflangs = [];

    foreach ($hreflangs as $lang => $url) {
        // Extract the part before the dash ('fr' from 'fr-FR')
        $part = explode('-', $lang, 2)[0];
        $newHreflangs[$part] = $url;
    }

    return $newHreflangs;
}

/**
 * Hook into Falang hreflang generation
 */
add_filter('falang_hreflang', 'change_hreflang');

3 – How it works

Falang generates an array of hreflang values like this:

[
    'fr-FR' => 'https://example.com/fr/',
    'en-US' => 'https://example.com/en/',
]
  • The function change_hreflang() replaces each key (e.g. fr-FR) by its language code only (fr).
  • The filter add_filter('falang_hreflangs', 'change_hreflang') tells Falang to use your modified array

Result:

After adding this code, your site will output simplified hreflang tags like this:

<link rel="alternate" href="https://example.com/fr/" hreflang="fr" />
<link rel="alternate" href="https://example.com/en/" hreflang="en" />

instead of:

<link rel="alternate" href="https://example.com/fr/" hreflang="fr-FR" />
<link rel="alternate" href="https://example.com/en/" hreflang="en-US" />

Optional – Keep full code for specific languages

If you want to keep the full code for certain languages (like zh-CN or pt-BR), you can modify the function like this:

function change_hreflang(array $hreflangs): array {
    $keepFull = ['zh-CN', 'pt-BR']; // list of locales you want to keep
    $newHreflangs = [];

    foreach ($hreflangs as $lang => $url) {
        if (in_array($lang, $keepFull, true)) {
            $newHreflangs[$lang] = $url;
        } else {
            $part = explode('-', $lang, 2)[0];
            $newHreflangs[$part] = $url;
        }
    }

    return $newHreflangs;
}