How to log in a WordPress user programmatically

Sometimes, while building WordPress based websites, you might face a situation where you want to login a user automatically. This can be easily done using following code snippet.

See Also: How to check if user is logged in or a visitor in WordPress?

Paste the following code in your functions.php file.

//Log in a WordPress user programmatically
function auto_login( $user ) {
    $username   = $user;
    if ( !is_user_logged_in() ) {
        $user = get_user_by('login', $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 );

To log in the user, do the following.




    • Hey Rachel,
      Thank you for commenting! 🙂

      I am not sure about how cookies are saved but I think their are saved somewhere in %AppData% folder for most of the browsers.

      Also, If we don’t set the $remember parameter to true, it will not remember the user. Again, I am not sure, I will get back to you as soon as I find the correct answer.


Leave a Comment.