Development,  WordPress

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:
[postad1]

 $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:
[postad2]

 '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...
}

[postad3]
As you see, nothing easier!

Leave a Reply

Your email address will not be published. Required fields are marked *