Redirect User based on role or capability on login

Redirect user based on role or capability on login. You can add else if’s to direct different users. has_cap accepts roles or capabilities. So you could use, “edit_posts” for a check.

Add to functions file.

/**
 * WordPress function for redirecting users on login based on user role
 */
function my_login_redirect( $url, $request, $user ){
    if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
        if( $user->has_cap( 'administrator' ) ) { // this can be role, or capability
            $url = admin_url();
        } else {
            $url = home_url('/members-only/');
        }
    }
    return $url;
}

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

Leave a Reply

Your email address will not be published. Required fields are marked *

63 + = 72