Redirect users away from Admin breaks ajax

Tried to make a simple redirect for some users I don’t want to access the wp-admin/, so I did this code:

function no_admin_access() {
    if ( !current_user_can( 'delete_posts' ) ) {
        wp_redirect( site_url( '/' ) ); exit;
    }
}
add_action('admin_init', 'no_admin_access');

But when I then try to make a ajax request with those users, the that is also redirected so I never get to admin-ajax.php

Read More

Anybody who has a good work around for this ?

Thanks.

AJAX Code

$.ajax({
    type: 'POST',
    url: MyAjax.ajaxurl,
    data: {
        action: 'mux_ajax_delete_pix',
        pid: $this.attr('data-id')
    },
    success: function(){
        $this.parent().fadeOut();
    }
});

Related posts

Leave a Reply

2 comments

  1. You can and a check for the DOING_AJAX constant which is defined on an Ajax in your conditional check:

    function no_admin_access()
    {
        if (
            // Don't do this for AJAX calls
            ! defined( 'DOING_AJAX' ) 
            // Capability check
            && ! current_user_can( 'delete_posts' ) 
            )
        {
            // Redirect to home/front page
            wp_redirect( site_url( '/' ) );
            // Never ever(!) forget to exit(); or die(); after a redirect
            exit;
        }
    }
    add_action( 'admin_init', 'no_admin_access' );
    
  2. i’m using below function and it is working fine for me

    function remove_admin_access_for_non_editor() {
    if ( is_admin() && ! current_user_can( 'edit_posts' ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
    wp_redirect( home_url() );
    exit;
    }
    }
    add_action( 'init', 'remove_admin_access_for_non_editor' );