developer
developer

Reputation: 658

wp_ajax_nopriv not working wordpress

My ajax is not working on the front end such that wp_ajax_nopriv not working, when user is logged in, the ajax is working fine, but when there is an opposite scenario such that user/admin is logged out, the page is redirecting to main home page and ajax is not working for the non logged in users. How to fix my problem, and access the same ajax for both scenarios. Im using wordpress 4.0 currently. Is there any possible way to restrict the ajax to work for every scenario?

My Code:

add_action( 'wp_ajax_Test_SO', 'Test_SO' );
add_action( 'wp_ajax_nopriv_Test_SO', 'Test_SO' );

function Test_SO()
{
 $a = array('1','2','3');
        wp_send_json_success( $a );
}

Upvotes: 1

Views: 2231

Answers (1)

indextwo
indextwo

Reputation: 5935

If it's redirecting to your homepage, it sounds like a filter is being used to prevent non-admin users from accessing the wp-admin area. Something like this is quite common, usually in a plugin or in the functions.php file:

function filterNonAdmins() {
    if (!current_user_can('manage_options')) {
        wp_redirect(home_url());
        exit;
    }
}

add_action('admin_init', 'filterNonAdmins');

...however this is bad, because it also filters AJAX calls.

What you need is something more akin to this:

function filterNonAdmins() {
    if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
        if (!current_user_can('manage_options')) {
            wp_redirect(home_url());
            exit;
        }
    }
}

add_action('admin_init', 'filterNonAdmins');

This checks to see whether it's an AJAX call first; if it is, then the user/call isn't redirected.

Upvotes: 3

Related Questions