Trying to figure out the functionality of setting cookies for a language portal.
Basically, have a page containing all available languages for users when they first come to the site. I want to store their selection in a cookie, and the user would then be redirected to his chosen language on subsequent visits.
My code is as follows:
For the button: <a onClick="<?php Cookie::set('language_select', $available_lang->code(), ['lifetime' => 1440]); ?>"
In the index.php:
if(Cookie::exists(‘language_select’)) {
// not sure how to send user to correct language page if cookie is set
echo (new Kirby)->render(‘home’);
} else {
echo (new Kirby)->render(‘global-landing’);
}
You are mixing PHP and JS code in a way that is not possible (calling a PHP backend function in the onClick frontend attribute of an anchor tag); also, relying purely on a JavaScript onClick event is not accessible.
Instead, your landing page could feature a link to each language’s front page: <a href="/en">English</a>. This guide has some ideas how to auto-generate such a list from the Kirby setup.
In the template/controller of your landing page (assuming that’s the root of the domain in this example), all you do is to redirect users with a set language cookie to the according home page (the go() helper is what you need here, triggering an HTTP 302 redirect):
if (Cookie::exists('language_select')) {
// NB. this relies on the cookie containing a valid language
// code; you may want to validate that
go('/' . Cookie::get('language_select'));
}
In the template/controller of the language landing pages (like example.com/en) you set the cookie to the according language – which can be retrieved from Kirby’s language object:
Cookie::set('language_select', $kirby->language()->code(), ['lifetime' => 1440])
// lifetime is given in minutes, i.e. using this value it only works for 24h
This could – and for good UX probably should – of course be developed further, but I hope this gives you a minimal prototype to get started with?!