I am having an issue with setcookie. I need to set a cookie on a page action (form).

I have tried on the template file, but not working.

then find out if I set it from functions.php with init hook, it's working.

then I put condition like


then it's not working.

how can I do that?

here is my code.

add_action( 'init', 'hello_my_cookie' );

function hello_my_cookie() {
            setcookie( 'myCookie','Hello Cookie!', time()+3600);

1 Answer 1


This fails because the init hook is far too early to call is_page_template. Conditionals such as this function use the main query to decide their value, but WordPress hasn't created the main query yet.

The earliest hook you can safely do this is template_redirect.

  • Thank you! but is there any other way to do this without calling the init hook? I have tried to set the cookie from the template file. but it does not work. Can you suggest any other way? Commented May 31, 2022 at 22:10
  • 1
    Thank you! it worked! Commented May 31, 2022 at 22:27

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.