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();
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 bothwp_set_auth_cookie()
andwp_clear_auth_cookie()
.Use the following code
Reference wp_set_auth_cookie and wp_set_current_user
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.