DEV Community

Cover image for What is a WordPress Nonce? And how to use it.
Simon Lee
Simon Lee

Posted on • Edited on

What is a WordPress Nonce? And how to use it.

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.

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')
));
Enter fullscreen mode Exit fullscreen mode

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);
  }
})
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay