Is there a hook that fires before an ajax call?

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x