doulang6695 2014-09-03 17:27 采纳率: 100%
浏览 39
已采纳

wp_signon无法正常工作,因为移动到下一页时没有用户登录

In my wordpress project I am have created template page where user can register. Now Problem I am facing is making user logged in after registration. I have created a user and after that I have tried to make the user log in using below code.

$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );

I have also created a log in template to allow user loged in by using same above code but same issues occurs. Now problem I am facing is as soon as I moved to new page, I found user is not logged in.

I guess cookies are not getting saved. I have also tried using

wp_set_auth_cookie($user->ID,true);

But no success.

I cannot understand when we logged in using wp-admin then one can successfully logged in or if I am using wp_login_form() then that also works fine. Then wats is the problem by using above code.

Please help as I have to anyhow make user logged in after registration.

  • 写回答

2条回答 默认 最新

  • dongrendang6566 2014-09-03 17:42
    关注

    Your code is correct. Both pieces of code will authenticate and login the user succesfully.

    However you are missing the redirect. After calling wp_signon() or wp_set_auth_cookie(), you should redirect the user to make sure the new cookie is being loaded.

    This can be done by using the following code right after your wp_signon() or wp_set_auth_cookie() call:

    wp_redirect($_SERVER['REQUEST_URI']);
    exit;
    

    In case you want to redirect the user to a specific page, you can replace $_SERVER['REQUEST_URI'] with the URL where you want to redirect the user to.

    A sidenote: you should make sure that this code is called before the headers are being sent, as wp_redirect() will not work after the headers are sent.

    EDIT: In case the above does not work, you might try the entire login process ($user should be the user object, which you can get with the get_user_by() function):

    do_action('wp_login', $user->user_login, $user);
    wp_set_current_user( $user->ID );
    wp_set_auth_cookie( $user->ID );
    $redirect_to = $_SERVER['REQUEST_URI'];
    wp_safe_redirect($redirect_to);
    exit;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?