0

I was in the process of building a plugin and stumbled on the page in the codex for the login_redirect filter, where I found this particular example :

function my_login_redirect( $redirect_to, $request, $user ) {

    //is there a user to check?

    if ( isset( $user->roles ) && is_array( $user->roles ) ) {

        //check for admins

        if ( in_array( 'administrator', $user->roles ) ) {

            // redirect them to the default place

            return $redirect_to;

        } else {

            return home_url();

        }

    } else {

        return $redirect_to;

    }
}

add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );

My question is why is it important to check whether the user role is set and if the output is an array before we can check if the value we want lies in the array or not?

In my knowledge, every user will have a default role and the roles property is an array data type as mentioned on the WPUser class reference page (https://codex.wordpress.org/Class_Reference/WP_User -> check under Public Properties).

All in all, cant we simply do something like :

if (in_array('administrator', $user->roles)) {
    return $redirect_to;
} else {
    return $home_url;
}

Is there something conceptual to programming that I am missing out on?

1

Because only the first parameter is required, and $user might be a WP_Error object if the person trying to log in isn't a valid user.

$user (WP_User or WP_Error) (optional) WP_User object if login was successful, WP_Error object otherwise. Default: None

  • Makes sense. But what about the checking of isset($user->roles) ? Dont all Wordpress users have a default role? – Ram Iyer May 16 '17 at 18:30
  • You can technically remove all roles from a user. I haven't tested to see if this results in an empty value or an empty array. I usually err on the side of safety and make no assumptions about what I'm dealing with. – Milo May 16 '17 at 18:42

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.