Set a cookie inside the 404.php theme page

admin2025-06-04  2

I'm trying to set a cookie with these code but the cookie is not created

setcookie( 'name', 'carl', 0, '/names', '', isset($_SERVER["HTTPS"]), true);

I was looking on the internet a possible solution and I found and try this solution

add_action( 'init', 'wpse8170_init' );
function wpse8170_init() {
    if ( !headers_sent() ) {
        setcookie( 'name', 'carl', 0, '/names', '', isset($_SERVER["HTTPS"]), true);
    }
}

But it didn't work. Please help, I just need a way to create a cookie inside my 404.php theme page and then I will make a redirection to another page of my own website, as the cookie is just to keep the variable for the next page.

I'm trying to set a cookie with these code but the cookie is not created

setcookie( 'name', 'carl', 0, '/names', 'https://my.webdomain', isset($_SERVER["HTTPS"]), true);

I was looking on the internet a possible solution and I found and try this solution

add_action( 'init', 'wpse8170_init' );
function wpse8170_init() {
    if ( !headers_sent() ) {
        setcookie( 'name', 'carl', 0, '/names', 'https://my.webdomain', isset($_SERVER["HTTPS"]), true);
    }
}

But it didn't work. Please help, I just need a way to create a cookie inside my 404.php theme page and then I will make a redirection to another page of my own website, as the cookie is just to keep the variable for the next page.

Share Improve this question asked Jan 13, 2019 at 4:03 Lester VargasLester Vargas 1035 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

I think the template files load too late, try setting it in the functions.php file.

add_action( 'init', 'wpse325439_init' );
function wpse325439_init() {
    if ( !headers_sent() && is_404() ) {
        setcookie( 'name', 'carl', 0, '/names/', 'my.webdomain', isset($_SERVER["HTTPS"]), true);
    }
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749016773a315648.html

最新回复(0)