I have customized a plugin to make some ajax calls to admin-ajax.php and it works great. I copied the code over to another site and it no longer works for users who are not logg
change condition to
!user_can($current_user->ID, 'administrator') && ( !user_can($current_user->ID, 'contributor') ) && !is_ajax()
add !is_ajax()
I had something similar occur in a theme. The original coder was trying to prevent a non-admin user from being able to see the /wp-admin/ area.
Here's an example:
// Block Access to /wp-admin for non admins.
function custom_blockusers_init() {
if ( is_user_logged_in() && is_admin() && !current_user_can( 'administrator' ) ) {
wp_redirect( home_url() );
exit;
}
}
add_action( 'init', 'custom_blockusers_init' ); // Hook into 'init'
I would check your theme for source code similar to what I have.
When you find the code, just add an extra conditional to make sure that a user isn't redirected if the DOING_AJAX constant is defined.
I know this is still a old question but you can have a look.
LETS DO THE CODE FASTER IF NOT INTERESTED ON EXPLANATION:
function redirect_non_admin_user(){
if ( !defined( 'DOING_AJAX' ) && !current_user_can('administrator') ){
wp_redirect( site_url() ); exit;
}
}
add_action( 'admin_init', 'redirect_non_admin_user' );
EXPLANATION: The reason for this problem is that either some of the installed plugins are redirecting the non admin users to homepage or any pages when they try to access wp-admin like http://localhost/project/wp-admin . So this causing the problems .
SO when you redirecting non admins from accessing admin ,you can use the following code.This will also work in admin ajax call in frontend.
I had the exact same problem and this worked for me:
function mt_redirect_admin() {
if ( ! current_user_can( 'manage_options' ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
wp_redirect( site_url() );
exit;
}
}
add_action( 'admin_init', 'mt_redirect_admin', 1 );