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() );

About Antonia Whitaker

An administrative, sales and marketing background has given me an understanding of what users want from their website. I do not confuse issues with technical jargon and I listen to what people want.

19. January 2015 by Antonia Whitaker
Categories: Wordpress | Tags: | Leave a comment

Leave a Reply

Required fields are marked *