A nonce by definition is something that is used only once and without recurrence. In a WordPress website, nonces are used to validate the contents of a form and avoid malicious activity. More specifically, a nonce protects your website from Cross-Site Request Forgeries (CSRFs) attacks.
- source: this blog article
How to use a nonce in WordPress
In functions.php, in your function that loads scripts and css files, you can create a nonce property inside a WordPress function called wp_localize_script()
. See example below:
wp_localize_script('my-website-files', 'someSiteData', array(
'nonce' => wp_create_nonce('wp_rest')
));
If you view your web page source, you can find a key-value that looks similar to: var someSiteData = {"nonce": "15e935b62e"}
You can use that generated hash as a property in an AJAX request, as shown below:
// jQuery
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', someSiteData.nonce);
}
})
Top comments (0)