functions – Setcookie not setting cookies anywhere except admin
I want to set various cookies from the URL query string. I am checking for the GET values and then printing the desired values and then trying to set the value in the cookies.
function on_page_load() {
if(array_key_exists('utm_source',$_GET)) {
$query_string = $_SERVER['QUERY_STRING'];
$query_vars = explode("=",$query_string);
$utm_source = explode("&",$query_vars[1])[0];
$utm_medium = explode("&",$query_vars[2])[0];
$utm_campaign = explode("&",$query_vars[3])[0];
$utm_term = $query_vars[4];
error_log($utm_source);
error_log($utm_medium);
error_log($utm_campaign);
error_log($utm_term);
setcookie('utm_source', $utm_source, time()+60*60*24*365, "https://wordpress.stackexchange.com/");
setcookie('utm_medium', $utm_medium, time()+60*60*24*365, "https://wordpress.stackexchange.com/");
setcookie('utm_campaign', $utm_campaign, time()+60*60*24*365, "https://wordpress.stackexchange.com/");
setcookie('utm_term', $utm_term, time()+60*60*24*365, "https://wordpress.stackexchange.com/");
file_put_contents(WP_PLUGIN_DIR . "test.txt",$_GET);
file_put_contents(WP_PLUGIN_DIR . "test1.txt",$_GET['utm_source']);
}
}
The above code is printing all the desired values to the log as well as all the values from the $_GET superglobal are getting shown in the file where I have put the contents.
The code is setting all the cookies for the admin dashboard. Our website is hosted on the Cloudways DO server.
I have tried the following:
- Clearing the cache of the website and the browser
- Trying several browsers
- Purging LiteSpeed Cache and Breeze Cache
- Deactivating LiteSpeed Cache and Breeze Plugins
- Switching between values from the query string using $_GET and $_SERVER
- Trying to use httponly mode.
The cookies are getting set when I am logged in to the admin account, elsewhere they are not getting set. I have this code inside a function getting called upon by the init hook, and the following code:
add_action('init','on_page_load',10);
Any help or guidance regarding the solution or the correct path is most welcome. Thanks.
Leave an answer