after login that will redirect user role into a page

I am trying to create a hook that when a user login, it check the user role.. if the user role is jsa_contributor then it redirect into specific page. but it seems my code didn’t work.

This is the code..

function my_login_redirect($login) {
    $data_login = get_option('axl_jsa_login_wid_setup');
    $redirect_page = $data_login[0];

    $logout_redirect_page = $data_login[1];

    $current_user = get_user_by('login',$login);
    if($current_user->roles == 'jsa_contributor'){
        wp_redirect(get_permalink($redirect_page)); /* Redirect browser */
        exit();
    }
}

add_action('wp_login', 'my_login_redirect', 99);

does anyone have an idea about this? thanks in advance…

Solutions Collecting From Web of "after login that will redirect user role into a page"

OK, so your first problem is that $current_user->roles is an array and not a string, so your condition won’t be true 😉

My another concern would be the hook you’re using. Some plugins may use it for other purposes, and killing the script can be harmful. And… there is much better hook for this 😉

First solution: using login_redirect hook

function my_login_redirect( $redirect_to, $request, $user ) {
    //is there a user to check?
    global $user;
    if ( isset( $user->roles ) && is_array( $user->roles ) ) {

        if ( in_array( 'jsa_contributor', $user->roles ) ) {
            // redirect them to the default place
            $data_login = get_option('axl_jsa_login_wid_setup');

            return get_permalink($data_login[0]);
        } else {
            return home_url();
        }
    } else {
        return $redirect_to;
    }
}
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );

But you have to remember, that this code would redirect users only after loging in. It won’t restrict users to access wp-admin.

If these users shouldn’t be able to get to wp-admin, then you should use another method…

Second solution: restricting wp-admin access

function my_restrict_wpadmin_access() {
    if ( ! defined('DOING_AJAX') || ! DOING_AJAX ) {
        $user = wp_get_current_user();

        if ( isset( $user->roles ) && is_array( $user->roles ) ) {
            if ( in_array('jsa_contributor', $user->roles) ) {
                $data_login = get_option('axl_jsa_login_wid_setup');
                wp_redirect( get_permalink($data_login[0]); );
                die;
            }
        }
    }
}
add_action( 'admin_init', 'my_restrict_wpadmin_access' );