使用wp_LOGIN与LOGIN_REDIRECT进行基于用户元的重定向

时间:2017-08-25 作者:Dovid Levine

我编写了一个函数,使用login_redirect, 而且效果很好。然后我将挂钩更改为wp\\u login(以使其与社交登录插件配合使用),现在该功能正在重定向通过wp_login_form.

PS:通过我的社交登录插件登录时,重定向工作正常。

Is there a difference between wp_login and login_redirect, or is something wrong with the conditional php?

代码如下:

//Hook was working fine when it was login_redirect
add_action( \'wp_login\', __NAMESPACE__ .\'\\\\gsc_login_redirect\', 10, 3 );

function gsc_login_redirect() {
    $user = wp_get_current_user();

    //Check if a redirect parameter was passed with the url. 
    $redirect_to = isset($_GET[\'redirect_to\'])? $_GET[\'redirect_to\']: \'\';

    //Set fallback redirect
    if ( isset( $user->roles ) && is_array( $user->roles ) ) {
        if(!isset($redirect_to) || $redirect_to == \'\'){
            if (in_array( \'administrator\', $user->roles ) ) {
                $redirect_to = admin_url();
            }
            else $redirect_to = home_url();
        }
    }

    wp_redirect( first_time_login( $redirect_to, $user) );
    exit();
}

//Redirect user if it\'s their first time logging in.
function first_time_login( $redirect_to, $user){
    if( $user->user_profile_setup == \'true\'){ //meta is set to true after user submits form on /account-setup
        return $redirect_to;
    }
    else{
        return "/account-setup?redirect_to=\'". $redirect_to . "\'";
    }
}
发生的情况是,所有用户都被重定向到“/帐户设置”,即使在$user->user_profile_setup 是“true”。

有什么想法?

1 个回复
SO网友:deflime

你确定吗$user->user_profile_setup 引用元信息的正确方法是什么?

# does \'user_profile_setup\' show up under wp_get_current_user()?
print_r(wp_get_current_user());
我想你的意思是:

function first_time_login( $redirect_to, $user){
  if( get_user_meta($user->ID, \'user_profile_setup\', true) == \'true\' ){ //edited line
    return $redirect_to;
  }
  else{
    return "/account-setup?redirect_to=\'". $redirect_to . "\'";
  }
}
假设

$current_user = wp_get_current_user();
print_r(get_user_meta($current_user->ID));
输出

Array
(
  ...
  [user_profile_setup] => Array
    (
      [0] => true
    )
  ...
)

结束

相关推荐