Log in a WordPress user programmatically

With this snippet you can log in a WordPress user automatically.

<?php

function auto_login( $user ) {
    $username   = $user;
    // log in automatically
    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 );
    }     
}
?>

3 comments

  1. avatar
    wrote this comment on
    Thanks. A quick word for anyone else who comes upon this. It's going to attempt to output headers and redirect the user to the backend. Depending on where you're using this you may not want that to happen. I know I didn't. Since many Wordpress users out there aren't always the most technically inclined in my opinion is worthy to note that you may need to use output buffering for the correct behavior.

    function auto_login( $user ) {
    ob_start();
    $username = $user;
    // log in automatically
    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 );
    }
    ob_end_clean();
    }



    This isn't a better or alternative method. But use it if you're trying to get the above code to work after headers have been output and you're not trying to redirect the user.
  2. avatar
    wrote this comment on
    For anyone wanting to do this in v2.5 or later take a look at http://codex.wordpress.org/Function_Reference/wp_signon as this has replaced the wp_login function.

    Cheers
  3. avatar
    wrote this comment on
    Here is a WordPress Auto Login tutorial I created the other day

    http://carlofontanos.com/auto-login-to-wordpress-from-another-website/

    hope it helps.

Start a new thread

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.