0

I'm doing a simple login redirect to a custom admin page using the following code:

function my_login_redirect( $redirect_to, $request, $user ) {
    if ( is_array( $user->roles ) ) {
        if ( in_array( 'administrator', $user->roles )  || in_array( 'shop_manager', $user->roles ) ) {
            return admin_url( 'admin.php?page=welcome-page.php' );
        } else {
            return admin_url();
        }
    }
}
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );

However, I am getting the error:

Notice: Undefined property: WP_Error::$roles

the line it refers to is if ( is_array( $user->roles ) ) {

this seems to be the recommended way in the WordPress docs - what could be going wrong here?

  • I remember having difficulties with this myself with one project - I seem to have this in the code which seems roundabout but not sure why else I would have put it in like so: global $user; $user_id = $user->ID; $userObj = get_userdata($user_id); to then get the object properly. You can then $userObj->roles to get roles array. – Bysander Feb 16 '16 at 12:42
2

Looking at PhpDocs for login_redirect filter I found out that the third param could be a WP_Error object instead of a WP_User:

$user WP_User object if login was successful, WP_Error object otherwise.

So a working code sample for you would be:

function dls160216_login_redirect( $redirect_to, $request, $user ) {
    if ( ! is_wp_error( $user ) ) {
        // do redirects on successful login
        if ( $user->has_cap( 'administrator' ) || $user->has_cap( 'shop_manager' ) ) {
            return admin_url( 'admin.php?page=welcome-page.php' );
        } else {
            return admin_url();
        }
    } else {
        // display errors, basically
        return $redirect_to;
    }
}
add_filter( 'login_redirect', 'dls160216_login_redirect', 10, 3 );

Note that I used has_cap method. It's more future-proof and allows for better filtering. Can verify a capability or a role.

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.