I am trying to implement custom login on wordpress. To do this:
- I have added an action to the wp_loaded event in which I do my custom authentication and once user is authenticated, I have following code to set the auth cookie:
wp_set_current_user( $user_id ); wp_set_auth_cookie( $user_id );
Now if I test this code with /wp-admin as the URL this is what happens:
- the code is executed and I verified
wp_set_auth_cookieis called - subsequently there is a call to auth_redirect from admin.php
- Within this call there is a call to wp_validate_auth_cookie and that fails to pass
The result is that user is redirected to login page whereas this should not happen. I want wp_validate_auth_cookie to pass. I think the reason for this behavior is that wp_set_auth_cookie will set the cookie in the HTTP response and its only in any subsequent request from the browser that the cookie will be set in the HTTP request. However that ruins my test case.
Is there any way to:
- suppress the
auth_redirectfrom admin.php - or make
wp_validate_auth_cookiereturn true
or anything else that can be done so that user is not redirected to login page when they try to access /wp-admin?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
If you want the login works without having to reload the page (or redirect to somewhere on the site), then you would want to immediately set both the auth and logged-in cookies, i.e. set them in the superglobal $_COOKIE array. And you can do that via the set_auth_cookie and set_logged_in_cookie hooks:
add_action( 'set_auth_cookie', function ( $cookie ) {
$cookie_name = is_ssl() ? SECURE_AUTH_COOKIE : AUTH_COOKIE;
$_COOKIE[ $cookie_name ] = $cookie;
} );
add_action( 'set_logged_in_cookie', function ( $cookie ) {
$_COOKIE[ LOGGED_IN_COOKIE ] = $cookie;
} );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0