Blog

It can definitely get a little laborious to create, send, and verify nonces manually with every AJAX request in WordPress. Thankfully, there’s an easier way. In this post we’re going to take a look at an easy to set up solution that will automatically send nonces along with every request.

I’m not sure who invented this technique, but the first place I saw it was in Laravel‘s boilerplate JS file.

1. Create a nonce at the top of every page containing AJAX calls

It’s easy enough to do this. Simply add an action to wp_head that injects a meta tag with a nonce. You can add this to functions.php, or wherever makes sense in your plugin or theme.

3. Create a helper function that verifies your general nonce

Now, in your AJAX endpoints, you’ll want to verify the presence and value of your general nonce. While you could write that verification code separately inside every ajax call, I like to just create a helper function that includes all the logic. Drop this into your functions.php file.