DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

When building WordPress based websites, it can be very useful to know how to programmatically log in an user. Here is a reusable function to do it easily.

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!

One Comment

  1. wp_set_auth_cookie() and do_action( ‘wp_login’ ) are parts of wp_signon(), but wp_signon() also does a few other things. I think it’d be more correct and future-proof to just call wp_signon() instead of bits and pieces of it.

    Also, get_userdatabylogin() was deprecated in 3.3, so it’s better to use get_user_by() now.

    So, here’s my version of it: https://gist.github.com/iandunn/8162246

    It may look a bit more complicated because of the ‘authenticate’ filter callback and extra error-checking, but I think in reality it’s actually simpler. It’s just using wp_signon() and wp_set_current_user() to do the heavy lifting, rather than relying on partially duplicating the internals of wp_signon().

    WIth either approach you have to understand some of how Core works, but with this way you’re using the API rather than Core’s internals.

Leave a Comment

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