phpwordpresswordpress-login

How to log a user in to Wordpress using only their user_id


Is there any way I can log a Wordpress user in given only their wp user_ID?

I'm sending users emails to confirm something and when they click on the given link to come to the website they need to be logged in to see the page I'm taking them to, so I have to log the user in and then do a header redirect.

I need a php function provided by wordpress, one that I can use in php, could you also give me any extra details as to how I can implement it (if any)


Solution

  • Here a function to auto-log an user (not tested) :

    function auto_login() {
        if (!is_user_logged_in()) {
            //determine WordPress user account to impersonate
            $user_login = 'guest';
    
           //get user's ID
            $user = get_userdatabylogin($user_login);
            $user_id = $user->ID;
    
            //login
            wp_set_current_user($user_id, $user_login);
            wp_set_auth_cookie($user_id);
            do_action('wp_login', $user_login);
        }
    }