Log in a WordPress user programmatically

Here is the function, drop it in your functions.php file:

function auto_login( $user ) {
    $username = $user;
    if ( !is_user_logged_in() ) {
        $user = get_userdatabylogin( $username );
        $user_id = $user->ID;
        wp_set_current_user( $user_id, $user_login );
        wp_set_auth_cookie( $user_id );
        do_action( 'wp_login', $user_login );
    }     
}

Then, to log in a user, do the following:

auto_login( 'admin' )

Thanks evilsocket for the code!

Leave a Reply

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