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?

Read more here: Why is it important to check for isset and is_array before checking in_array in this example?


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: