You don’t need to check is_admin
because the function is hooked to admin_init
, so is_admin()
is always true
in the callback; that makes that ( is_admin() || !empty(DOING_AJAX) )
always verify as true
. You only need to check if the constant DOING_AJAX
is not defined or if it is defined and it is false
(both cases are not an AJAX request), combined with the user role. For example, to allow AJAX and access only to administrator
role:
add_action( 'admin_init', 'redirect_user' );
function redirect_user() {
$user = wp_get_current_user();
if( ( !defined('DOING_AJAX') || ! DOING_AJAX ) && ( empty( $user ) || !in_array( "administrator", (array) $user->roles ) ) ) {
wp_safe_redirect(home_url());
exit;
}
}
Also, you can consider to check capabilities instead of roles. For example:
add_action( 'admin_init', 'redirect_user' );
function redirect_user() {
if( ( !defined('DOING_AJAX') || ! DOING_AJAX ) && ( ! current_user_can('manage_options') ) ) {
wp_safe_redirect(home_url());
exit;
}
}