Can I programmatically login a user without a password?

Question:
Can I programmatically login a user without a password? I'm manually creating users programmatically, and I want to sign in the newly created user. WP makes it easy to access the hashed password, but not the plaintext version. Is there a way to use wp_signon() without the plaintext password?

Answer:
The following code does the job for automatic login, without any password!

// Automatic login //
$username = "Admin";
$user = get_user_by('login', $username );

// Redirect URL //
if ( !is_wp_error( $user ) )
{
    wp_clear_auth_cookie();
    wp_set_current_user ( $user->ID );
    wp_set_auth_cookie  ( $user->ID );

    $redirect_to = user_admin_url();
    wp_safe_redirect( $redirect_to );
    exit();
}

No comments:

Post a Comment