0

The following code should redirect the user to a specific page if they have the manage_woocommerce capability or higher - but it doesn't and just goes to the main dashboard.

    add_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 );
    public function login_redirect( $redirect_to, $request, $user ) {

        if( is_user_logged_in() == 1 ) {

            if( $user->has_cap( 'manage_woocommerce' ) ) {

                $redirect_to = get_admin_url() . 'admin.php?page=my-page';

            }

        }

        return $redirect_to;

    }

I have tried $user->has_cap, current_user_can with the same result.

1

OK, it wasn't easy to catch, but... There is one major problem in your code...

First check you make is:

if ( is_user_logged_in() == 1 ) {

And is_user_logged_in() is based on global $current_user variable. But... As you can read in login_redirect hook docs:

The $current_user global may not be available at the time this filter is run. So you should use the $user global or the $user parameter passed to this filter.

So this condition won't be satisfied - so your code won't change anything.

You should use $user variable that is passed as param, so this should do the trick:

public function login_redirect( $redirect_to, $request, $user ) {

    if ( is_a ( $user , 'WP_User' ) && $user->exists() ) {

        if ( $user->has_cap( 'manage_woocommerce' ) ) {

            $redirect_to = get_admin_url() . 'admin.php?page=my-page';

        }

    }

    return $redirect_to;
}
add_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 );
1

Your code is fine, but you're calling the is_user_logged_in() function too early. It will only work after another page load. So here's a simplified and efficient version to achieve the functionality:

add_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 );

public function login_redirect( $redirect_to, $request, $user )
{
    if ( $user instanceof WP_User && user_can( $user, 'manage_woocommerce' ) ) {
        $redirect_to = get_admin_url() . 'admin.php?page=userexplorer-userify';
    }

    return $redirect_to;
}

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.