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' );
}
So if I visit url like: www.domain/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.
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.
Answering my own post here, it seems that WP Super Cache has a dedicated setting (in Advanced section) to not cache urls that have a GET parameter. Once that is checked, problem seems not to replicate for me anymore.
So indeed the root problem is that cached files do not run the php code anymore, hence setting cookie from php fails and probably JS is a better option.
There might be other ways around it to force cookie setting specifically, look for example at wpsc_add_cookie functionality.
value
query. However, please consult the documentation or support articles/forums/site for the caching plugin that's used on your site. – Sally CJ Commented Mar 3, 2021 at 17:02