0

I wrote a function to redirect first-time users using login_redirect, and it was working great. Then I changed the hook to wp_login (to get it to play well with a social login plugin), and now the function is redirecting all users who sign in via the wp_login_form.

PS: the redirect works fine when logging in via my social login plugin.

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

Here's the code:

//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 . "'";
    }
}

What's happening is all users are being redirected to '/account-setup', even when $user->user_profile_setup is "true".

Thoughts?

0

Are you sure $user->user_profile_setup is the correct way to reference the meta info?

# does 'user_profile_setup' show up under wp_get_current_user()?
print_r(wp_get_current_user());

I think you mean to do:

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 . "'";
  }
}

Assuming that

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

Outputs

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.