I use only “pages” from my WP installation (not posts) and I want to set a cookie based on the existence of a GET parameter in the URL.
I have put the following code in the top of my page.php:
if ( get_query_var('value') ) {
$value=get_query_var('value');
setcookie( 'value',$value, time() + 2592000, COOKIEPATH, 'domain.com' );
}
So if I visit url like: www.domain.com/page/?value=1234 I want to have a cookie: value: 1234 set for this domain.
The problem is that this doesn’t work all the time (seems to be working about 70% of the time), and sometimes the cookie is not set.
I have Autoptimize and WP Super Cache plugins enabled, and CF as CDN.
What I tried:
I’m far from expert in WP, but I understand that there is also the option to add a function to functions.php with the same purpose, but I didn’t managed to make it work at all like this.
Does it matter where in the body of page.php I put this code (should it be more down so that it always get executed?), or is there any other way to make sure the code is executed all the time.
I know that there are ways of setting cookie from JS as well, but I would preffer to do it from php.