Contact

WPML, Polylang, Wordpress

Apprenez à créer un site multilingue avec nous

Find Us

Afterglow Web Agency
5, rue Alexandre Dumas
06100 Nice
France

Adding hreflang tags on a WordPress + WPML blog

01 10 2021 By Cédric Moris Kelly

IndexingWordpress

If you have a multilingual site under WordPress and WPML, by default, the hreflang tags that are so useful for referencing your pages are not created on the blog page.

Here is a function that you can paste in the functions.php file of your theme to fix this.

/**
* Add Hreflang Link on Blog Page
* @hooks on wp_head
* @return string 
* Author : Afterglow Web Agency
*/
function afg_hreflangOnBlog() {
    if(!function_exists('icl_get_languages')) return;

    if(is_home()) {
        $defaultLanguage = apply_filters('wpml_default_language', NULL );
        $siteLanguages = icl_get_languages('skip_missing=1&orderby=code');
        
        foreach ($siteLanguages as $l) {
            $code = $l['language_code'];
            echo $code != $defaultLanguage ? 
                '<link rel="alternate" hreflang="'.$code.'" href="'.get_post_type_archive_link( 'post' ).'/'.$code.'/">' 
                : 
                '<link rel="alternate" hreflang="'.$code.'" href="'.get_post_type_archive_link( 'post' ).'">';
        }
    }
}

add_Action( 'wp_head', 'afg_hreflangOnBlog');

This code will add all the hreflang tags corresponding to the languages of your site in the head of your blog page. It doesn’t matter if the blog is the homepage of your site or an internal page.

To be fully compatible with WPML this code should retrieve the url schema configured in WPML. Indeed some people use subdomains rather than subdirectories for the different languages of their website.
This code supports languages configured in subdirectories.
If you want an example with subdomain management, just send us a message!