I use wp_signon() and it returns a user, not an error. However when I do is_user_logged_in() it returns false.
I am trying to get current user info by using get_currentuserinfo() and wp_get_current_user() but getting user info as false. I googled this issue and got the solution which can help others also.
Actually after using wp_signon(), the user info is not set, which is how WP checks for a user in is_user_logged_in().So for getting user info after sign in from wp_signon function we have to set current user manually by using wp_set_current_user()
Successful code snippet is as follows:
1 2 3 4 5 6 | $creds = array( 'user_login' => $_POST['username'], 'user_password' => $_POST['pwd'], 'remember' => $_POST['rememberme'] ); $user = wp_signon( $creds, false ); if ( is_wp_error($user) ): echo $user->get_error_message(); endif; wp_set_current_user($user->ID); echo $user->display_name; // for getting display name from user return $user; |
wp_signon() function authenticates a user with option to remember credentials.
1 | <?php wp_signon( $credentials, $secure_cookie ) ?> |
Parameters:
$credentials
(array) (optional) User info in order to sign on.
Default: None
$secure_cookie
(boolean) (optional) Whether to use secure cookie.
Default: None
Return : if login fails it returns WP_Error object and on success WP_User object.
Note: After using this functio, user info is not being set. so set it manually.
Hey I found your blog to be quite informative. I have been using custom wp theme built on bootstrap. I am just a novice in wp development. I am using a plugin called Ultimate member. Using that I’m able to add Login as menu item. I wanted to display the name of logged in user after successful login. Can you please let me know how that can be done ?
website url: prepfocus.in
Hey,
you have to put this code where you wish to display his/her name.
if (is_user_logged_in()) {
$current_user = wp_get_current_user();
echo $current_user->display_name;
}