1

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!

2 Answers 2

1

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 ...

0

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.

1
  • Even if I do this, cookie isn't detected on the main page. It still shows only on the specific URL ... I checked the documentation, but still can't figure it out :/
    – Alex
    Commented Dec 1, 2018 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.