Hello.
I can see Polylang sets the HTML lang to es-ES
, but sets the hreflang attribute to es
. I believe this is because you’re not using different locales, but I understand you do not need this setup.
According to Google’s recommendations, for the hreflang, it is better to use the language code on its own, without the country code. However, if you want to override this, Polylang has a filter called pll_rel_hreflang_attributes
.
The Polylang documentation for pll_rel_hreflang_attributes
is here: https://polylang.pro/doc/filter-reference/#pll_rel_hreflang_attributes
Here’s a snippet you can add to your theme’s functions.php
file to apply a filter for the Spanish and Italian hreflang attributes:
// Polylang hreflang filter
function filter_pll_rel_hreflang_attributes( $hreflangs ) {
foreach ( $hreflangs as $lang => $url ) {
if ( $lang === 'es' ) {
printf( '<link rel="alternate" href="%s" hreflang="%s" />' . "\n", esc_url( $url ), esc_attr( 'es-ES' ) );
}
if ( $lang === 'it' ) {
printf( '<link rel="alternate" href="%s" hreflang="%s" />' . "\n", esc_url( $url ), esc_attr( 'it-IT' ) );
}
}
return $hreflangs;
};
add_filter( 'pll_rel_hreflang_attributes', 'filter_pll_rel_hreflang_attributes', 10, 1 );
This should give you something similar to this:
<link rel="alternate" href="https://example.com/" hreflang="it-IT" />
<link rel="alternate" href="https://example.com/es/" hreflang="es-ES" />
<link rel="alternate" href="https://example.com/" hreflang="it" />
<link rel="alternate" href="https://example.com/es/" hreflang="es" />
Hope this helps!