php redirect with custom user roles set and working but redirect not working for when users are logged in

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;
    }
}

Topic php Wordpress

Category Web


If the user is logged-in, the function returns before the redirect code lower in the function.

if( is_user_logged_in() ) {
    return;
}

Since you want the redirect code to run only if the user is logged in, try this:

if( ! is_user_logged_in() ) {
    return;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.