D
D
Damaks2015-09-19 14:40:40
CMS
Damaks, 2015-09-19 14:40:40

Problem displaying cookie value?

Hello.
The theme's functions.php file specifies the creation of a cookie:

add_action( 'init', 'create_cookie' );
function create_cookie() {
    // если кукиша нет или он пустой, создаём его с дефолтным значением
    if(!$_COOKIE["my_cookie"] || empty($_COOKIE["my_cookie"])) {
        setcookie( 'my_cookie', 'value', time()+7776000);
    };
}

But in the theme template itself, the value is not displayed. Or rather, the created cookie is not located, although the cookie is displayed correctly in the browser debugger. If you paste this code in your theme file:
if(!$_COOKIE["my_cookie"]) {
    echo '0';
}
elseif(empty($_COOKIE["my_cookie"])) {
    echo '1';
}
else {
    echo '2';
}

Then the first time the page is visited, 0 is displayed.
When the page is refreshed, 2 is displayed.
It seems that the cookie is created after requesting it on the page, which cannot be. Moreover, the choice of an earlier event at which create_cookie is executed does not affect the situation (if a cookie is created, of course).
What can be wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question