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

孤人 提交于 2019-12-03 12:13:01

问题


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)


回答1:


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);
    }
}



回答2:


You have to pass 2 parameters in wp_login hook. See Wp codex

wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user->user_login, $user );



回答3:


Create separate table to store all the links you sent and respective temp authentication code, which may be valid only for some time, then pass that temp auth code and email as a url param -

Write a code to validate user based on temp auth code, so that as soon as user clicks on email you can redirect him.




回答4:


That's a really bad ideea. Consider this: You send an email to user A and B which contains the following link:

http://wordpressblog.exp/fromemail?user_id=A;
http://wordpressblog.exp/fromemail?user_id=B;

If user B replaces his user id with A's user_id then he has access to User A's account. Youd be better of constructing a hash for logging a user that way



来源:https://stackoverflow.com/questions/10041583/how-to-log-a-user-in-to-wordpress-using-only-their-user-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!