Skip to content

Multilingual WordPress URL strategy and hreflang, with the Polylang API

Choose the URL structure for a multilingual WordPress site, then emit or correct hreflang in code: pll_languages_list, pll_the_languages, the pll_rel_hreflang_attributes filter, and getting Yoast's canonical to agree.

If you arrived here from pll_languages_list(), the short version is that it is a template function, not a filter. It takes one arguments array whose documented keys are fields and hide_empty, and it returns the list of languages Polylang knows about — slugs by default. The thing you pass to apply_filters() for hreflang is a different name entirely: pll_rel_hreflang_attributes, which hands you the array Polylang is about to print in the document head, keyed by hreflang code with the URL as the value. Everything around that code — whether your French pages live at /fr/, at fr.example.com or behind ?lang=fr, and whether Yoast’s canonical agrees with what the multilingual plugin emitted — decides whether those tags get honoured at all.

This article is the URL-structure decision plus the code that emits or corrects the tags. If your tags already exist and Search Console is unhappy with them, the diagnostic companion is WordPress hreflang for multilingual sites, which covers what each report actually means.

What you’ll accomplish

  • Choose deliberately between subdirectory, subdomain, country domain and query-parameter URLs, knowing what each costs in certificates, Search Console properties and cache keys.
  • Read the language set out of Polylang in PHP using only documented signatures.
  • Ship a language switcher two ways: the one-call version, and a hand-rolled one that survives untranslated posts.
  • Add x-default and region-qualified codes such as fr-CA to the emitted hreflang set through a filter, without editing the plugin.
  • Prove canonical and hreflang agree on every language, and that the page cache is keyed on language.

Prerequisites

  • WordPress 6.x on PHP 8.1 or newer, with pretty permalinks already enabled. Everything below assumes the site is not on plain permalinks.
  • Polylang 3.x, free or Pro. The function and filter names used here come from the Polylang function and filter references; confirm each against the version actually installed before shipping, and guard with function_exists().
  • Shell access with WP-CLI and curl. Several checks cannot be done from the admin at all.
  • A writable wp-content/mu-plugins/ directory. Filters belong there, not in functions.php, so a theme switch cannot silently drop your hreflang corrections.
  • Search Console verified for whichever properties the URL structure implies — part of the decision below, not separate from it.
  • A staging copy. Changing the URL structure on a live site rewrites every translated URL: a redirect project, not a settings toggle.

How it works

Two independent things are in play. The URL structure decides how a crawler, a CDN and a certificate authority each see your languages. The hreflang tags decide which of those URLs are declared equivalent. Getting the second right on top of a bad choice for the first is wasted effort.

Four URL structures for a multilingual WordPress site compared as small topologies — subdirectory, subdomain, separate country domain and query parameter — each annotated with certificate scope, Search Console properties, cache key behaviour and geo signal strength

Subdirectory (example.com/fr/page/) is the default answer for almost every site. One hostname means one certificate, one Search Console property covering every language, and a cache key that already contains the path — so /fr/page/ and /page/ are naturally distinct cache entries with no configuration. Its only real weakness is that it gives no per-country signal beyond whatever the single domain already carries.

Subdomain (fr.example.com/page/) buys the ability to host a language somewhere else, which matters if the French site runs on different infrastructure or a different team’s release cadence. It costs a wildcard or multi-name certificate, and either one Search Console property per subdomain or a single domain property covering them all. The cache key contains the host, so language separation is again automatic.

Separate country domains (example.fr) give the strongest country association and are the right call when you genuinely operate per country, with different legal entities, prices or catalogues. They cost the most: a certificate per domain, a Search Console property per domain, separate DNS, and either multisite or separate installs. That is a business decision with an SEO side effect, not the other way around.

Query parameter (example.com/page/?lang=fr) is what Polylang falls back to when permalinks are plain, and it is the one structure to move off. Most CDN and page-cache configurations strip unknown query strings from the cache key, which means the first visitor to request ?lang=fr can populate the cache entry for /page/ — and every later visitor gets French regardless of what they asked for. Search Console reports also fold parameter variants together, so the language breakdown you want to read is not there.

On the tag side, hreflang can live in three places, and Google treats all three as equivalent: link rel="alternate" elements in the document head, Link: HTTP response headers, or xhtml:link children inside an XML sitemap. Pick one. Emitting from two places is how sets end up disagreeing.

Three rules decide whether a set is honoured. Every page in the set must carry a self-referencing tag pointing at itself. Every page must point at every other page in the set. And the pointing must be mutual — if page A claims page B is its French version but page B says nothing about A, the claim is discarded, because otherwise any site could annex any URL. x-default is the fallback for visitors whose language matches nothing you publish, and it belongs on a language-picker home page or on the default-language entry point.

Codes are ISO 639-1 language, optionally followed by an ISO 3166-1 Alpha 2 region. fr and fr-CA are both valid and are not interchangeable: fr-CA targets French speakers in Canada, fr targets them anywhere. For a Quebec-facing site that also sells into France, publishing only fr-CA means visitors in France match nothing and fall through to x-default. Polylang emits whatever code the language was configured with, often the bare fr, so region qualification is usually a filter’s job.

Step-by-step

1. Confirm what structure the site is actually on. Check permalinks, then ask a parameter URL what it does.

wp option get permalink_structure
curl -sI 'https://example.com/?lang=fr' | head -1

On a correctly configured directory-mode site the first command prints something like /%postname%/ and the second prints a redirect:

/%postname%/
HTTP/2 301

A 200 on the second line means parameter URLs are live and indexable alongside your pretty ones. Fix that in Polylang’s Languages, Settings, URL modifications panel first, and treat it as a redirect project: every already-indexed ?lang= URL needs a 301 to its pretty equivalent.

2. Read what the plugin already emits. Do this before writing any code, on one page per language.

for u in https://example.com/page/ https://example.com/fr/page/ https://example.com/es/page/; do
  echo "== $u"
  curl -s "$u" | grep -o 'hreflang="[^"]*"' | sort -u
done

A healthy three-language set prints the same four values under each URL:

== https://example.com/page/
hreflang="en"
hreflang="es"
hreflang="fr"
hreflang="x-default"

Three values under one URL and four under the others is a return-tag failure — fix that before anything else here.

3. Read the language set in PHP. Four functions cover almost every switcher and audit script.

$slugs   = pll_languages_list( array( 'fields' => 'slug', 'hide_empty' => 1 ) );
$names   = pll_languages_list( array( 'fields' => 'name' ) );
$current = pll_current_language( 'slug' );
$default = pll_default_language( 'slug' );

pll_languages_list() documents exactly two argument keys, fields (default slug) and hide_empty (default 0). Anything else you see in a forum snippet should be verified against your installed version before you rely on it. pll_current_language() and pll_default_language() both take a single field name, defaulting to slug, and return one value rather than a list.

4. Ship the one-call switcher first. pll_the_languages() takes a single arguments array and prints a list.

add_action( 'sh_language_switcher', function () {
    if ( ! function_exists( 'pll_the_languages' ) ) {
        return;
    }
    pll_the_languages( array(
        'display_names_as'       => 'name',
        'show_names'             => 1,
        'show_flags'             => 0,
        'hide_current'           => 0,
        'hide_if_no_translation' => 0,
        'echo'                   => 1,
    ) );
} );

hide_if_no_translation is the argument worth thinking about. Left at 0, a language with no translation of the current post links to that language’s home page. Set to 1, the language disappears from the switcher. Neither is wrong, but the second hides your coverage gaps from the only people who would notice them.

5. Hand-roll the switcher when you need control over the fallback. This is the pattern behind most pll_languages_list() searches: build the list yourself so you decide what happens when a translation is missing.

$slugs   = pll_languages_list( array( 'fields' => 'slug' ) );
$current = pll_current_language( 'slug' );

foreach ( $slugs as $slug ) {
    $target = '';

    if ( is_singular() ) {
        $translations = pll_get_post_translations( get_the_ID() );
        if ( isset( $translations[ $slug ] ) ) {
            $target = get_permalink( $translations[ $slug ] );
        }
    }

    if ( ! $target ) {
        $target = pll_home_url( $slug );
    }

    printf(
        '<a href="%s" hreflang="%s"%s>%s</a>',
        esc_url( $target ),
        esc_attr( $slug ),
        $slug === $current ? ' aria-current="page"' : '',
        esc_html( strtoupper( $slug ) )
    );
}

pll_get_post_translations() returns an array keyed by language slug whose values are post IDs, including the post you passed in. pll_home_url() takes a language slug and returns that language’s home URL — the honest fallback for an untranslated post. If you would rather adjust the built-in switcher than replace it, pll_the_languages filters the rendered output and pll_the_languages_args filters the arguments before rendering.

6. Correct the emitted hreflang set. This is where x-default and region codes get added.

The bidirectional hreflang graph for three pages — English, French Canadian and Spanish — each showing the four alternates it must emit including its own self-reference and x-default, with one broken edge marked as a missing return tag

add_filter( 'pll_rel_hreflang_attributes', function ( $hreflangs ) {
    $default = pll_default_language( 'slug' );

    if ( isset( $hreflangs[ $default ] ) ) {
        $hreflangs['x-default'] = $hreflangs[ $default ];
    }

    if ( isset( $hreflangs['fr'] ) ) {
        $hreflangs['fr-CA'] = $hreflangs['fr'];
        unset( $hreflangs['fr'] );
    }

    return $hreflangs;
} );

The array arrives keyed by hreflang code with the absolute URL as the value, and whatever you return gets printed. Note the ordering: x-default is copied from the default language before fr is renamed, so renaming cannot strand it.

7. Make Yoast agree with the multilingual plugin. Yoast emits the canonical; Polylang or WPML emits the hreflang. They are supposed to be complementary, and the failure mode is the canonical pointing across languages, which tells Google to drop the translation you just annotated.

for u in https://example.com/page/ https://example.com/fr/page/; do
  echo "== $u"
  curl -s "$u" | grep -o 'rel="canonical" href="[^"]*"'
done

Each URL must name itself:

== https://example.com/page/
rel="canonical" href="https://example.com/page/"
== https://example.com/fr/page/
rel="canonical" href="https://example.com/fr/page/"

If the French page canonicals to the English one, a manual canonical was typed into the Yoast advanced panel and copied when the translation was created. Clear it. WPML ships a Yoast glue plugin and Polylang Pro carries its own Yoast support; on free Polylang, leave Yoast’s automatic self-canonical alone.

8. Decide the sitemap shape, once. Either one sitemap per language, each listing only that language’s URLs, or one sitemap carrying xhtml:link annotations. Do not run both, and do not run two sitemap plugins. Check what is actually being served:

curl -s https://example.com/sitemap_index.xml | grep -o '<loc>[^<]*</loc>'
curl -sI https://example.com/wp-sitemap.xml | head -1

The second command should print HTTP/2 404 on a site where Yoast or Rank Math has correctly disabled the core sitemap. A 200 there means two generators are live, which is its own problem — see WordPress sitemap conflicts when multiple plugins are active.

Validate it works

Walk the actual translation graph rather than trusting the tag output, because the tags are generated from it:

wp eval '
$langs = pll_languages_list( array( "fields" => "slug" ) );
echo "languages: " . implode( ",", $langs ) . "\n";
foreach ( get_posts( array( "post_type" => "page", "numberposts" => 5, "fields" => "ids" ) ) as $id ) {
    $t = pll_get_post_translations( $id );
    printf( "%-6d %-6s %s\n", $id, pll_get_post_language( $id ), implode( ",", array_keys( $t ) ) );
}'
languages: en,fr,es
12     en     en,fr,es
19     en     en,fr
27     en     en
34     en     en,fr,es
41     en     en,fr,es

Post 19 is missing Spanish, post 27 has none at all. Those are content gaps, not tag bugs, and they surface in Search Console weeks later.

Then confirm the cache is not the thing serving the wrong language:

curl -sI https://example.com/fr/page/ | grep -iE 'content-language|x-cache|cf-cache-status|vary'
curl -sI https://example.com/page/     | grep -iE 'content-language|x-cache|cf-cache-status|vary'

Each should report its own content-language. If the French URL ever answers content-language: en, the cache key is not separating them.

Troubleshooting

Tags present one way but not the other. Page A lists B, B says nothing about A, Google discards the pair. The usual cause is a translation that is a draft, trashed, or noindex — the source still emits the alternate while the target emits nothing. Publish it or remove the link; the WP-CLI loop above finds these faster than the tag output does.

?lang= URLs indexed alongside pretty permalinks. These accumulate before anyone switches Polylang to directory mode and persist afterwards because nothing redirects them. Find them with a site: query, then add 301s to the pretty equivalents. Do not use robots.txt: blocking crawl leaves the indexed URLs in place with no way for Google to see the redirect.

Canonical fighting hreflang. The tags are perfect and the translations still do not rank, because a cross-language canonical is quietly instructing Google to consolidate them. Run the canonical check in step 7 on every language, not just one.

Page cache serving the wrong language. The most under-diagnosed failure on this list. If the language is carried in a cookie or a query parameter rather than in the path, and the cache key does not include it, whichever language warms the cache first is what everyone gets — and it is intermittent, which is why it survives testing. Two fixes, in order of preference: move to path-based URLs so the language is in the key by construction; or, if you must keep a cookie, add that cookie to the cache key at the CDN and to the Vary header at the origin. Cache rules are a live-traffic change, so stage it and be ready to purge the zone.

x-default missing on the language picker. A home page that offers a choice rather than serving a language has to carry x-default, or visitors whose locale matches nothing get an arbitrary language version. The filter in step 6 handles this; verify it renders with curl -s https://example.com/ | grep -i x-default.

When this is the wrong approach

A two-language brochure site does not need any of this. Six pages in English and six in French can be one site with a manually maintained pair of link rel="alternate" tags in the header template, and neither WPML nor Polylang has to be involved. The plugin earns its cost when translations are numerous, edited by different people, and expected to stay in step — a content-workflow problem, not a tagging problem.

Machine translation with correct hreflang is still thin content: annotating a machine-translated page perfectly tells Google exactly where to find a page it has no reason to rank. If the French version is unreviewed output, the honest options are to publish fewer French pages and review them, or to hold French back — not to improve the tags.

And if the real driver is per-country pricing, legal terms or fulfilment, the URL question is downstream of a business decision. Pick country domains because you actually operate per country and accept the overhead, rather than adopting them for a signal you could get more cheaply.

Google’s own reference for the tag mechanics is Localized versions of your pages, and the authoritative list of Polylang template functions is the Polylang function reference.

Running WordPress that earns real money deserves an operator — Stack Harbor runs that stack under Enterprise WordPress; book an infrastructure consult.