Skip to main content
1 of 3

Remember language choice on multisite website

I have a multisite website with 3 websites representing 3 languages. On my network website https://example.com I have a page with 3 language choices linking to https://example.com/nl?language=nl, https://example.com/fr?language=fr and https://example.com/en?language=en.

The first time a user gets to https://example.com I want them to choose their language, redirect to the corresponding subsite and store that choice in a cookie. Next time the visitor goes to https://example.com he should be redirected automatically to the subsite stored in the cookie. Obviously if someone goes directly to https://example.com/nl/... nothing should happen.

I tried adding this code in the functions.php in my child-theme, but it doesn't work at all. What am I doing wrong?

// if a cookies is set and the user is on https://example.com/, redirect to the saved language subsite
if (isset($_COOKIE['language'])) {
    $pagename = $_SERVER['REQUEST_URI'];
    if ($pagename == '/') {
        wp_safe_redirect("https://example.com/".$_COOKIE['language']);
        exit;
    }
}

// if the user choose a language save a cookie
if (isset($_GET["language"])) {
    setcookie('language', 1, time() + 1209600, "/", "https://example.com/".$_GET['language']."", false); // Set the chosen language
    wp_safe_redirect("https://example.com/".$_GET['language']); // redirect to the chosen language
    exit;
}

Thanks a lot!

Mark