0

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;
}

UPDATE This was the final code that worked:

if (isset($_COOKIE['language'])) {
    $pagename = $_SERVER['REQUEST_URI'];
    if ($pagename == '/') {
        wp_safe_redirect("/".$_COOKIE['language']);
        exit;
    }
}

if (isset($_GET["language"])) {
    $language = sanitize_text_field($_GET["language"]);
    setcookie('language', $language, time() + 1209600, "/", "example.com", false);
}

Thanks a lot!

Mark

0

setcookie() has the following signature:

setcookie ( $name, $value = "", $expires = 0, $path = "", $domain = "", $secure = FALSE, $httponly = FALSE )

You're setting the cookie's value to 1 in your code. I suspect you intend to do something more like

setcookie('language', $_GET['language'], time() + 1209600, "/", "example.com", false);

Notes

  • This answer doesn't address the security issues in trusting that the $_GET data is clean. You should research data sanitization.
  • WordPress provides a bunch of handy constants to make something like time() + 1209600 easier to read. You can do something like time() + ( 2 * WEEK_IN_SECONDS ), for example.
1
  • 1
    Thanks! That did the trick. I also added 'sanitize_text_field', see update in question. – netcult Nov 24 '20 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.