2 years ago

#10883

test-img

Mike Jandreau

Adding hreflang tags automatically in WordPress multisite

I've managed to write a function that gets the job done, but I feel like there has to be a better way to do this.

I have a WordPress multisite network that is running with the subdirectory setup. There's a primary site that is in English and several sub-sites that have been mostly translated to other languages. Translation is ongoing and there is not an equivalent page/post for each site in the network yet. For a post that exists on the English site that is not yet on the Spanish site, an hreflang tag for website.com/some-blog-post will return a 404 for website.com/es/some-blog-post.

I've placed this function in the theme's functions.php file for the time being. The site theme is made with Timber/Twig and there is no header.php file, so to add this to a template or partial would require some structural refactoring. I'm using the 2-letter code as a text string for easy insertion to both the hreflang and corresponding subdirectory in the URL.

This seems like the most workable solution given the limitations, although PHP isn't my strong suit. If there is a better way I'm all for it.

 /**
 * ADD HREFLANG ATTRIBUTES
 * Automatically append hreflang with network URL, language, and permalink to all pages
 */
function add_hreflang_attribute() {
    $site_url = "network_site_url()"; // base URL 
    $alt_langs = array( 'de', 'es', 'fr' ); // two-letter language code
    $page_path = substr(get_permalink(), strlen(home_url('/'))); // path of page after base URL

    // get primary English site URL and page path
    echo '<link rel="alternate" href="' . $site_url . $page_path . '" hreflang="en" />'. PHP_EOL;

    // loop through the alternative languages, and get the appropriate hreflang tag for each that exists
    foreach ($alt_langs as $lang) {
        $updated_url_lang_path = $site_url . $lang . '/' . $page_path;
        $url_headers = @get_headers($updated_url_lang_path);
        if($url_headers && strpos( $url_headers[0], '200')) {
            echo '<link rel="alternate" href="' . $updated_url_lang_path . '" hreflang="' . $lang . '" />'. PHP_EOL;
        }
    }

    // set primary as x-default
    echo '<link rel="alternate" href="' . $site_url . $page_path . '" hreflang="x-default" />';
}
add_action('wp_head', 'add_hreflang_attribute', 1);

Again, it works, but I'd like to make this better if I can. Preemptive thanks for any pointers, and Happy New Year!

php

wordpress

multisite

hreflang

0 Answers

Your Answer

Accepted video resources