Plugin Author
Phil
(@philsbury)
Hi @tlash,
You’re not far off there, but you probably want to set the cookie when the form is submitted. This assumes you’re on the PHP version:
/**
* Pretty much what you have already
*/
add_filter('pre_age_gate_custom_fields', 'my_ag_custom_zip', 10, 1);
function my_ag_custom_zip($fields)
{
$fields .= '<label for="ag_field_zip" class="ag_field_zip_label">Please add your zip code</label></br>';
$fields .= '<input type="text" id="ag_field_zip" name="ag_field_zip" class="ag_zipcode" placeholder="zip code" value="" maxlength="12" size="12"/></br>';
$fields .= age_gate_error('ag_field_zip');
return $fields;
}
Then handle the submission:
/**
* An action on the form success hook
*/
add_action('age_gate_form_success', 'set_zip_cookie');
function set_zip_cookie()
{
// make sure this is sanitized and/or validated
$zip_field = $_POST['ag_field_zip'] ?? '';
if (!isset($_COOKIE['ag_zip'])) {
setcookie('ag_zip', $zip_field, time()+31556926);
}
}
If you’re on the JS version, that’d be a bit different and less easy in the current version. Would be possible though.
Thanks
Phil
Thread Starter
tlash
(@tlash)
Thanks! that works great. There’s another issue but i will open separate item.
Thread Starter
tlash
(@tlash)
Hi Phil,
Turns out I do need some guidance on a JS version as our server cache requires i use JS.
When I use the code above, I see the cookie is set in the browser cookie, but when I inspect with dev tools it’s not there. Switching off JS and then I see the cookie in dev tools.
Thanks in advance.
Plugin Author
Phil
(@philsbury)
Hi @tlash,
You’ll need some JS functions it you’re using the JS version, something like this will work:
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
window.addEventListener('agegatepassed', function () {
var zip = document.getElementById('ag_field_zip');
if (zip) {
setCookie('ag_zip', zip.value);
}
});
I’ve rolled that code up in this package that you can copy… or just install as a separate plugin, it also has some bits for your other thread, but I’ll reply there too!
Thanks
Phil
Thread Starter
tlash
(@tlash)
Phil,
You are awesome. thank you.