set cookies on certain page only

Question

I am trying to set a cookie on WordPress on a certain page only. I’ve tried a LOT of different ideas but still can’t get it to work as ‘init’ is called before the page is set.

This is my current code:

add_action('init', function() { 
    //if ( is_page( 2164 ) ) {  
        setcookie( "my_cookie", 'hello' );
    }
});

But of course is_page() won’t return the current page and nor does anything else I try.

I’ve looked at other suggestions on StackExchange (e.g. using ‘templateredirect’) but they don’t work for me either.

So has anyone any idea how I can set a cookie when a user hits a certain page only?

Thanks!

0
, arathra 4 years 2019-11-05T03:45:02-05:00 0 Answers 70 views 0

Leave an answer

Browse
Browse