I’ve created a dual language website with a form that when submitted saves a cookie, each page then checks the cookie to see what language to load.
The problem I’m having is that the submit buttons need to be pressed twice for it to load the page and switch the language.
This is the form I have:
<form action="<?php the_permalink(); ?>" name="region" method="post">
<input type="submit" name="region" value="English" id="en-button" />
<input type="submit" name="region" value="Cymraeg" id="cy-button" />
</form>
This is in my functions.php file to save the cookie:
function set_region_cookie()
{
if(isset($_POST['region']))
{
// Set Cookie
setcookie('region', $_POST['region'], time()+1209600);
// Reload the current page so that the cookie is sent with the request
header('Region: '.$_SERVER['REQUEST_URI']);
}
}
add_action('init', 'set_region_cookie');
And this is what I have around each content area to load the different content:
<?php $language = $_COOKIE["region"];
if ($language == "English") { ?>
<?php echo the_field('english_content'); ?>
<?php } else { ?>
<?php echo the_field('welsh_content'); ?>
<?php } ?>
The language switches correctly but only when you click the submit buttons twice.
Turns out that the problem arises as a result of the way that cookies work, found the following (vital) information in this question:
I never actually noticed at first, but there is actually a line of code in the question to deal with refreshing the page so that the server receives the cookie:-
Change that to: