How to auto login user with a link in WordPress

·

Recently, I was setting up a demo environment for the CrewHRM plugin. I needed to place a link on the demo website home page where people could click to log in. I did this to avoid sharing a username and password manually. This removed a little bit of friction from entering the details. So saving 2 seconds is a big deal!

Auto login code for WordPress

Here is the source code I found online to add an auto login feature to my demo site.

if( isset($_GET['username']) and $_GET['pass'] ) {
    $user = get_user_by('login', $_GET['username']);

    if ( $user && wp_check_password( $_GET['pass'], $user->data->user_pass, $user->ID) ) {
        wp_set_current_user($user->ID, $user->user_login);
        wp_set_auth_cookie($user->ID);
        do_action('wp_login', $user->user_login);

        wp_redirect( admin_url() );
        exit;
    }

    wp_redirect( home_url() );
    exit;
}

I added this in the themes function.php file

Auto login link for WordPress

The auto login link looks like this https://demo.getcrewhrm.com/wp-admin/?username=demo&pass=demo

Please note that I had to create an account with the credentials I have used in the link. There could be security issues with this method. Please use this code at your own risk. I take no responsibility.

Comments

Leave a Reply