I'm trying to set up, when a specific page/url is visited that a cookie is set and saved.
So far I've tried this:
add_action('init', 'set_cookie', 1);
function set_cookie(){
if ( $currentURL == '/' ) :
if ( ! isset( $_COOKIE['opt_in'] ) ) :
setcookie( 'opt_in', has_opt_in, time()+31556926);
endif;
endif;
}
Now, when I visit the specific URL, cookie is detected, but when I move on to another page, cookie is gone.
How can the cookie be saved?
I'm pretty new to this, please help me understand.
Thank you!
I'm trying to set up, when a specific page/url is visited that a cookie is set and saved.
So far I've tried this:
add_action('init', 'set_cookie', 1);
function set_cookie(){
if ( $currentURL == 'https://25dni.si/delovanje-uma/' ) :
if ( ! isset( $_COOKIE['opt_in'] ) ) :
setcookie( 'opt_in', has_opt_in, time()+31556926);
endif;
endif;
}
Now, when I visit the specific URL, cookie is detected, but when I move on to another page, cookie is gone.
How can the cookie be saved?
I'm pretty new to this, please help me understand.
Thank you!
I've used this and it works:
add_action('init', 'optin_cookie', 1);
function optin_cookie(){
$currentURL = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if ( $currentURL == 'https://25dni.si/delovanje-uma/' ) :
setcookie( 'opt_in', has_opt_in, time()+31556926, '/');
elseif ( $currentURL != 'https://25dni.si/' ) :
if ( ! isset( $_COOKIE['opt_in'] ) ) :
endif;
endif;
}
I'm sure there is a much more elegant way to do it, but this got it working for me ...
I'm surprised it works at all since $currentURL
is not defined in the function nor declared as a global.
Look at the documentation for setcookie()
. You did not declare a path for the cookie so try this:
setcookie('opt_in','opt_in', time()+31556926, '/');
That will set the cookie for the entire domain, if that's what you want to do.