Programmatically create and login user into WordPress
Is there a way to programmatically login user into WordPress? Well, of course yes. This is, in fact, very easy. WordPress does it every time you login! Even more, we may login without using any password. WordPress basically checks password hash and if it is correct, then log user in. We may just skip password hash comparing and jump straight into login.
I wrote some small plugin recently to join foreign Application with WordPress installation. User has to login into application and WP login layer has to be invisible. Here is how I did it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php /* * Check if user is really who he is by using * integration with another app API * Let's assume we have $user variable with * user's data and $user['element'] is app's id */ # we need some password, but we do not need to know it $user_password = wp_generate_password(32,TRUE); # we need email, it may be fake or we may get it from app $user_id = wp_create_user($user['element'],$user_password,$user['email']); # this is up to you, what you use as nickname wp_update_user([ 'ID' => $user_id, 'nickname' => $user['name'] . ' [' . $user['element'] . ']' ]); # so, now we may load newly created user $ready_user = new \WP_User( $user_id ); # set its role (I used subscriber) $ready_user->set_role('subscriber'); # now we may add App's data to our WP user add_user_meta( $user_id, 'Element', $user['elment'], TRUE ); add_user_meta( $user_id, 'AppData', $user, TRUE ); # and now most important part - logging in! wp_clear_auth_cookie(); wp_set_current_user ( $user_id ); wp_set_auth_cookie ( $user_id ); $redirect_to = home_url(); wp_safe_redirect( $redirect_to ); exit(); # and that's it! |
You may also want to know if user is already in our database. Very simple thing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php /* * Again, we assume we have $user variable with * user's data and $user['element'] is app's id */ # let's query our users to find our user $user_query = new \WP_User_Query( array( 'meta_key' => 'Element', 'meta_value' => $user['element'] , 'fields' => 'all' ) ); $user_exist = $user_query->get_results(); if ( is_array( $user_exist ) && ( 1 == count( $user_exist ) ) ) { #Yes! We may log user in! $wp_user = $user_exist[0]; wp_clear_auth_cookie(); wp_set_current_user ( $wp_user->ID ); wp_set_auth_cookie ( $wp_user->ID ); $redirect_to = home_url(); wp_safe_redirect( $redirect_to ); exit(); } else { # add user as in example above... } |
As you see, nothing easier!