Admin-ajax.php 302 error WordPress

I have a WordPress site and 2 kinds of users. Admins and subscribers. If a subscriber tries to access the wp-admin area I want him to redirect to the home page of the site. I have a function to do this but when I try to access a different page on the site, for example to post a comment somewhere, it loads the home page inside the page I currenly am and doesn’t post the comment and any other action I do. From the network errors I see admin-ajax.php 302 error. I understand that WordPress uses two different hooks for ajax, one for admin side and one for logged out user and it has something to do with my problem but I don’t understand how to fix it.

function mt_redirect_admin(){

if ( ! current_user_can( 'edit_events' ) ){
    wp_redirect( site_url() );
    exit;       
}
}
add_action( 'admin_init', 'mt_redirect_admin' );

Thanks in advance for any answers

Related posts

Leave a Reply

1 comment

  1. Solved:

    function mt_redirect_admin() {
    
    if ( ! current_user_can( 'edit_events' ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
        wp_redirect( site_url() ); 
        exit;
    }
    }
    
    add_action( 'admin_init', 'mt_redirect_admin', 1 );