Umair Malik
Umair Malik

Reputation: 1451

wp_set_auth_cookie not working in wordpress

I want to set user logged when he fulfill some requirements and I'm using following function to set cookies in which I'm passing user's id as parameter which is according to wp_users table. But somehow it's not setting user logged in. What's missing and what I should do to set user login and also I want to logout user on some conditions. Both functions are not working.

wp_set_auth_cookie(1)
wp_clear_auth_cookie();

Upvotes: 1

Views: 7880

Answers (3)

CodeRevolution
CodeRevolution

Reputation: 107

I faced a similar issue and worked on solving it for a couple of days. My solution was pretty interesting, I found out that the wp_clear_auth_cookie function was not working for me if it was called in a regular GET request. I was able to make it work only if I called it inside of a POST request.

I found this behavior weird and no other reference can be found to this on the web.

I hope it will help you guys.

Upvotes: 1

Nikola Ivanov Nikolov
Nikola Ivanov Nikolov

Reputation: 5062

You're most-likely calling these functions after all headers have already been sent to the browser, so in effect you can't send the logged-in cookies to the browser.

The most common error for this is that you try to log-in a user when rendering a shortcode - this will not work in most cases(certain server configurations will allow this, but it's best not to rely on it).

You can hook to the init action and move your logic in there, together with the call to both wp_set_auth_cookie() and wp_clear_auth_cookie().

Upvotes: 3

Igor Yavych
Igor Yavych

Reputation: 4228

Use the following code

wp_set_current_user($user_id); 
if (wp_validate_auth_cookie()==FALSE)
{
    wp_set_auth_cookie($user_id, true, false);
}

Reference wp_set_auth_cookie and wp_set_current_user

Upvotes: 2

Related Questions