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];
        setcookie('utm_source', $utm_source, time()+60*60*24*365, "");
        setcookie('utm_medium', $utm_medium, time()+60*60*24*365, "");
        setcookie('utm_campaign', $utm_campaign, time()+60*60*24*365, "");
        setcookie('utm_term', $utm_term, time()+60*60*24*365, "");
        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:

  1. Clearing the cache of the website and the browser
  2. Trying several browsers
  3. Purging LiteSpeed Cache and Breeze Cache
  4. Deactivating LiteSpeed Cache and Breeze Plugins
  5. Switching between values from the query string using $_GET and $_SERVER
  6. 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:


Any help or guidance regarding the solution or the correct path is most welcome. Thanks.

Varun 2 weeks 2023-05-17T15:35:00-05:00 0 Answers 0 views 0

Leave an answer