Is there a hook that fires before an ajax call?

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.

Leave a Comment