'php redirect with custom user roles set and working but redirect no

I have created code to add custom user rules. It works. However when I try to tie in the code for redirecting an already logged in user based on one test role, then it doesn't work. What am I missing in this in order to have it redirect, based on a user's role. Here is the code:

add_action('init', 'cloneRoleCompany');
function cloneRoleCompany(){
    global $wp_roles;
    if ( ! isset( $wp_roles ) )
        $wp_roles = new WP_Roles();

    $adm = $wp_roles->get_role('subscriber');
    //Adding a 'new_role' with all admin caps
    $wp_roles->add_role('company-admin', 'Company Admin', $adm->capabilities);
    $wp_roles->add_role('company', 'Company', $adm->capabilities);
    $wp_roles->add_role('user', 'User', $adm->capabilities);
}
function redirect_from_front_page() {
    $redirect_url  = '/user-dashboard';
    $expected_role = 'user';

    if( is_front_page() ) {
        return;
    }

    if( is_user_logged_in() ) {
        return;
    }
    

    $user  = wp_get_current_user();
    $roles = $user->roles;
    

    if ( in_array( $expected_role, $roles ) ) {
        wp_safe_redirect( $redirect_url );
        exit;
    }
}


Solution 1:[1]

You have condition is_user_logged_in() which prevents to get into the redirect part of code, only logged in user have a role.

if( is_user_logged_in() ) {
    return; // when user is logged in this is last instruction
}

// code below will not get executed
$user  = wp_get_current_user();
$roles = $user->roles;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1