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!
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!
Share Improve this question asked Nov 5, 2019 at 9:45 arathraarathra 451 gold badge1 silver badge3 bronze badges 1 |1 Answer
Reset to default 0Please try to create certain page template and set cookies
<?php
/*
Template Name: Certain Page
*/
setcookie('my_cookie', "hello", (time()+3600), "/");
get_header();
?>
wp
andtemplate_redirect
do not work? And btw, it's not "templateredirect". – Sally CJ Commented Nov 5, 2019 at 9:50