1

I know that when use setcookie() function it create headers, and after refresh it will be available in $_COOKIES, but i need a mechanism to set cookie in this page without redirect, but to be in the browser cookie. If make something like this

setcookie('my_cookie','tmp_val');
$_COOKIE['my_cookie'] = 'tmp_val;

It is good for case when you set at once, but when you set cookie on each refresh in PHP is good but in browser cookie remains old. I try something like this

add_action('parse_request', function($tmp){
            setcookie('my_cookie','tmp_val');
            wp_safe_redirect(get_permalink());
            exit();
        });

but I have problems. Please help me in order to find a good solution.

  • 2
    Why do you need to read it from the cookie if it's within the same request you set in? The whole point of cookies is to persist data between separate requests. – Milo Nov 19 '14 at 14:15
  • Because a want a session behavior from cookie,in order to retrieve after refresh, I can use session but the problem is that session after browser close is unset, I think i will use usermeta for this. – user1147145 Nov 19 '14 at 14:50
  • 2
    your question is confusing- you say you want it without refresh, then you say you want it after refresh. I have no clue what you're trying to accomplish honestly. – Milo Nov 19 '14 at 16:37
2

You need to use the 'init' hook similar to the following:

add_action( 'init', 'your_function');
function your_function() {
    setcookie('my_cookie','tmp_val');
    wp_redirect( get_permalink() ); 
        exit; 
    } 
}

You should add a conditional 'if' statement in there to prevent it redirecting on every page though!

eg.

   add_action( 'init', 'your_function');
    function your_function() {
        setcookie('my_cookie','tmp_val');
        if ($my_cookie == "???") { 
            wp_redirect( 'go here' ); 
            exit; 
            } else {
            wp_redirect( 'go somewhere else' ); 
            exit;
        } 
    }

Also consider the 'template_redirect' hook.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.