1

I'm using the standard admin-ajax.php method of doing ajax. So I have some functions like this:

add_action( 'wp_ajax_nopriv_ajax_load_data', 'ajax_load_data' );
add_action( 'wp_ajax_ajax_load_data', 'ajax_load_data' );

function ajax_load_data() {
    ...
}

I have many ajax functions. Is there a WordPress hook that fires before all of them? My objective is to check for a certain user role so that I can short circuit all ajax calls coming from the front end.

6

If you look into this file wp-admin/admin-ajax.php where the wp_ajax_ actions are called, you will find that the admin_init action is being called before it.

Here is how to return a different json object based on if the user is admin or not:

add_action( 'wp_ajax_testing', 'my_ajax' );
add_action( 'admin_init', 'my_ajax_checker', 10, 2);

function my_ajax_checker() {
    if( defined('DOING_AJAX') && DOING_AJAX && current_user_can('manage_options') ) {

        switch($_POST['action']) {
            case 'action1':
            case 'action2':
            case 'action3':
                echo json_encode(array('error' => false));
                die();
        }
    }
}

function my_ajax() {
    echo json_encode(array('error' => true));
    die();
}

In this example it checks your actions to see which Ajax action is being called if you are logged in using one of your actions it will always return this json response '{error:false}'. It exits immediately and the my_ajax function never gets called. Replace the response with whatever you need it to be.

DOING_AJAX isn't always defined when the action admin_init is being utilized so make sure to check if its defined first before checking its value.

| improve this answer | |
  • 1
    .... and that will kill all ajax requests not just his. to make it reasonable you will still need to check for the action being passed. – Mark Kaplun Oct 12 '17 at 3:55
  • @MarkKaplun, lol, yup good catch. Was just throwing out a quick example of how to intercept Ajax calls but I should probably make it less error prone and more to what the OP wanted. – JoeMoe1984 Oct 12 '17 at 4:07
  • Thanks, I can work with this and tailor it to suit my objective. Thanks man – somebodysomewhere Oct 12 '17 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.