Ajax queries are redirected (admin‑ajax.php 302)

I’ve just spent a lot of time working out why an ajax function was not working for non-logged in users.

I’d added an action add_action('wp_ajax_nopriv_my_function', 'my_function') and I’d made sure admin-ajax.php was localized wp_localize_script('ajax-post', 'wp-ajax', array('ajaxurl' => admin_url('admin-ajax.php')).

Unfortunately the call was made, but never returned. The reason was because admin-ajax.php was being redirected to the home_url. This had been done in one of my plugins. Unfortunately they’d used a sledgehammer approach to redirect all non-logged in users away from admin pages to the home page. I found a better approach for the redirection in WordPress StackExchange:

function my_admin_init(){
  if( !defined('DOING_AJAX') && !current_user_can('manage_options') ){
    wp_redirect( home_url() );
    exit();
  }
}
add_action('admin_init','my_admin_init');
Scroll to Top