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 logged in.
From firebug:
POST http://<subdomain>.<server>/wp-admin/admin-ajax.php 302 Moved Temporarily 1.08s
GET http://<subdomain>.<server>/ 200 OK
edit: The question is what could a theme possibly do to redirect ajax requests. The plugin has two hooks:
add_action( 'wp_ajax_em_ajax_getEvents', 'em_ajax_getEvents' ); // ajax for logged in users
add_action( 'wp_ajax_nopriv_em_ajax_getEvents', 'em_ajax_getEvents' ); // ajax for not logged in users
They both work fine on most sites, but one theme redirects requests from non logged in users somehow. Since these actions are specific to the plugin I am at a loss as to where to start looking.
SOLUTION: Big thanks to Ronald Huereca for the add_action( 'init'
solution, that”s exactly where the offending redirect was hooking in, in an attempt to protect the admin area. Now I just need to find a safe fix here that doesn’t compromise the theme’s admin area, but also doesn’t hamstring other plugins from allowing users to make anonymous ajax requests.
// stop users accessing the admin
add_action('init', array( $this, 'prevent_admin_access' ), 0);
function prevent_admin_access() {
if (strpos(strtolower($_SERVER['REQUEST_URI']), '/wp-admin') !== false) {
$current_user = wp_get_current_user();
if(!user_can($current_user->ID, 'administrator') && ( !user_can($current_user->ID, 'contributor') ) ){
wp_redirect(get_option('siteurl'));
}
}
}
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:
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:
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:
change condition to
add
!is_ajax()