Check where the request is coming from
Creating the nonce and using it in the AJAX call
Checking the nonce in PHP
Now that the nonce is created and passed through in the AJAX request we need to check it in the PHP function. In WordPress there are multiple ways of doing this but the best way to check a nonce in an AJAX callback is to use the
check_ajax_referer function. The first argument of this function is the ‘action’. In my examples above I created the nonces with the action bk-ajax-nonce. The second argument is the request argument used. In my examples above I passed the nonces with the argument security. You can check the nonce of either of the above examples with the following code.
By default above function call will terminate the script if the nonce is not found or incorrect. If you wish the function to return the result of the nonce check you can add false as the third argument.
Adding and checking nonces in your WordPress AJAX calls is pretty easy and will improve security of your plugin or theme. Be sure to add them. If you have any questions or tips, please share them by leaving a comment below.