WordPress Multisite: Redirect Users Based on Their Browser Language

Since I wrote the post about using the Multisite Language Switcher I got many questions asking how I “disabled” the main site “/” in my WordPress Multisite configuration.

The answer is simple: I did not disable it, but just created an own, small redirect theme to make sure every user accessing the main site “/” is redirected to the correct language URL – in my case either “/en/” or “/de/”.

The following source code isn’t completely from me. I remember that I just searched the web for a good solution and changed it as I needed it, but that’s a longer time ago. Therefore no idea where parts or this code are from originally.

Anyway, here is the source code of the file index.php of my redirect theme just as I use it on this WordPress site right now:

<?php
/**
 * The main template file.
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 *
 * @package WordPress
 * @subpackage Redirect
 */

/**
 * Detect browser language.
 *
 * @param array $allowed_languages An array of languages that are available on the site.
 * @param string $default_language Default language to use if none could be detected.
 * @param string $lang_variable Custom user language support. If not specified $_SERVER['HTTP_ACCEPT_LANGUAGE'] is used.
 * @param string $strict_mode If true (default) the whole language code ("en-us") is used and not only the left part ("en").
 * @return string The detected browser language.
 */
function get_lang_from_browser($allowed_languages, $default_language, $lang_variable = NULL, $strict_mode = TRUE) {
    // Use $_SERVER['HTTP_ACCEPT_LANGUAGE'] if no language variable is available
    if (NULL === $lang_variable)
        $lang_variable = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

    // Any info sent?
    if (empty($lang_variable))
        return $default_language;

    // Split the header
    $accepted_languages = preg_split('/,\s*/', $lang_variable);

    // Set default values
    $current_lang = $default_language;
    $current_q    = 0;
    // Now work through all included languages
    foreach ($accepted_languages as $accepted_language) {
        // Get all info about this language
        $res = preg_match(
            '/^([a-z]{1,8}(?:-[a-z]{1,8})*)'.
            '(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i',
            $accepted_language,
            $matches
        );

        if (!$res)
            continue;

        // Get language code and split into parts immediately
        $lang_code = explode('-', $matches[1]);

        // Is there a quality set?
        if (isset($matches[2]))
            $lang_quality = (float)$matches[2];
        else
            $lang_quality = 1.0;

        // Until the language code is empty...
        while (count($lang_code)) {
            // Check if the language code is available
            if (in_array(strtolower(join('-', $lang_code)), $allowed_languages)) {
                // Check quality
                if ($lang_quality > $current_q) {
                    $current_lang = strtolower(join('-', $lang_code));
                    $current_q = $lang_quality;
                    break;
                }
            }
            // If we're in strict mode we won't try to minimalize the language
            if ($strict_mode)
                break;

            // Cut the most right part of the language code
            array_pop($lang_code);
        }
    }

    return $current_lang;
}

$allowed_langs = array('en', 'de');
$lang = get_lang_from_browser($allowed_langs, 'en', NULL, FALSE);
header('Location: http://' . $_SERVER['HTTP_HOST'] . "/$lang/");

exit();
?>

So just create a new theme folder and copy the PHP code above (change the allowed languages if needed, of course) into a file named index.php.

Then you just need to create an additional dummy file style.css with some info about the theme. Otherwise WordPress won’t recognize your theme:

/*
Theme Name: Redirect
Theme URI: http://wordpress.org/extend/themes/redirect
Author: AB-WebLog.com
Author URI: http://www.ab-weblog.com
Description: Redirects
Version: 1.0
Tags: redirect
*/

That’s it: after you have seleted this new theme for your main site “/”, every user will automatically be redirected to the correct language version based on the browser language settings.

Do you use the Multisite Language Switcher or your blog, too?

This post is also available in Deutsch.

One thought on “WordPress Multisite: Redirect Users Based on Their Browser Language

  1. Thank you very much for publishing this – I was just about to start coding it but you’ve saved me the time – much appreciated! :-)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>