• Resolved fernandomullerjr

    (@fernandomullerjr)


    I have a blog in 2 languages:
    Brazilian Portuguese (pt-br)
    English

    I have identified some problems with Mismatched hreflang and HTML lang declarations.
    Instead of having the pt-br language in the hreflang, it only has pt.

    I currently use the Polylang plugin to use multiple languages ??on my blog.

    I have tested the Polylang configuration, deactivated and activated the plugin, but the problem continues to occur.

    What can I do?

    Code snippet where the lang and hreflang are incompatible:

    <html lang="pt-BR" prefix="og: https://ogp.me/ns#" data-lt-installed="true"><head><script src="https://pagead2.googlesyndication.com/pagead/managed/js/adsense/m202409230101/">
    <link rel="alternate" hreflang="pt">
    <link rel="alternate" hreflang="en">

    My configuration:

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
  • Thread Starter fernandomullerjr

    (@fernandomullerjr)

    in the meantime, I found the solution for my case
    I needed to adjust the php code
    I edited the functions.php file in my theme

    and added the code below:

    add_filter('language_attributes', 'custom_language_attributes', 10, 2);
    add_filter('pll_rel_hreflang_attributes', 'custom_hreflang_attributes');
    
    function custom_language_attributes($output, $doctype) {
    if (!function_exists('pll_current_language')) {
    return $output;
    }
    $language = pll_current_language('slug');
    
    if ($language === 'en' || $language === 'en-US') {
    return str_replace('lang="en"', 'lang="en-US"', $output); } elseif ($language === 'pt' || $language === 'pt-br') { return str_replace('lang="pt-BR"', 'lang="pt-br"', $output);
     } return $output;
    } function custom_hreflang_attributes($hreflang_attributes) { $modified_attributes = [];
    
     foreach ($hreflang_attributes as $lang => $url) { if ($lang === 'pt' || $lang === 'pt-BR') { $modified_attributes['pt-br'] = $url;
     } elseif ($lang === 'en' || $lang === 'en-US') { $modified_attributes['en-US'] = $url;
     } else { $modified_attributes[$lang] = $url;
     }
    }
    
    return $modified_attributes;
    }

    This code does the following:

    1. Keeps the lang attribute of the <html> tag as “en-US” for English pages.
    2. Sets the lang attribute to “pt-br” for Portuguese pages.
    3. Modifies the hreflang attributes of the <link> tags to use “en-US” for English and “pt-br” for Portuguese.

    Now everything is ok!

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.