How to prevent access to wp-admin for certain user roles?

I did try using the plugin Front End Users but this clashes with something as it prevents access to some front end pages. So I need to manually just set it so that anyone who isn’t one of two usernames (or roles) can’t access wp-admin.

Solutions Collecting From Web of "How to prevent access to wp-admin for certain user roles?"

Plugin

It’s basically just a user capability check, followed by a redirect in an exit call. It then redirects to the site the request came from.

<?php
! defined( 'ABSPATH' ) AND exit;
/* Plugin Name: (#66093) »kaiser« Deny Admin-UI access for certain roles */


function wpse66093_no_admin_access()
{
    $redirect = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : home_url( '/' );
    if ( 
        current_user_can( 'USER_ROLE_NAME_HERE' )
        OR current_user_can( '2ND_ROLE_NAME_HERE' )
    )
        exit( wp_redirect( $redirect ) );
}
add_action( 'admin_init', 'wpse66093_no_admin_access', 100 );

The accepted answer mentions User Role but actually uses the function for User Capability

Here’s the solution for User Roles

 function wpse66094_no_admin_access() {
    $redirect = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : home_url( '/' );
    global $current_user;
    $user_roles = $current_user->roles;
    $user_role = array_shift($user_roles);
    if($user_role === 'YOUR_USER_ROLE_HERE'){
        exit( wp_redirect( $redirect ) );
    }
 }

add_action( 'admin_init', 'wpse66094_no_admin_access', 100 );

Based on the answer provided by @kaiser (thank you btw), this is my working code, just in any case someone needs it. It is placed in functions.php file.

The condition used is, if the user can’t manage_options or edit_posts.

function wpse66093_no_admin_access() {
    $redirect = home_url( '/' );
    if ( ! ( current_user_can( 'manage_options' ) || current_user_can( 'edit_posts' ) ) )
        exit( wp_redirect( $redirect ) );
}
add_action( 'admin_init', 'wpse66093_no_admin_access', 100 );

With @kaiser’s answer I found you’ll need to utilize admin_menu hook over admin_init as it fires before the !user_can_access_admin_page() check in wp-admin/includes/menu.php otherwise if the user doesn’t have ‘read’ access to the dashboard they’ll just get the ‘You do not have sufficient permissions to access this page.’ page rather than being redirected.