Technology WordPress Tips & Tricks

WordPress Nonce: The What, The Why, The How

Nonces are a small but important piece of keeping WordPress form submissions secure. Here is a guide to the what, why, and how of WordPress nonces, so your custom forms and actions stay protected against misuse.

Nirav Mehta Nirav Mehta 4 min read
WordPress Nonce: The What, The Why, The How
secure-WordPress-website
Secure WordPress Websites

How secure is your WordPress website?

Matt Mullenweg says:

“WordPress is trusted to run sites for some of the largest and most security-conscious organizations in the world, including Facebook, SAP, Glenn Greenwald’s The Intercept, eBay, McAfee, Sophos, GNOME, Mozilla, MIT, Reuters, CNN, Google Ventures, NASA, and literally hundreds more.”

Don’t be fooled!

I’m not saying WordPress is not secure, but your WordPress website is only as secure as the plugins and themes you use.

As you can imagine, security vulnerabilities exposed in several popular plugins and themes act as fodder for WordPress trolls. But the problem is not WordPress, it’s the underlying development practices followed.

So, what security measures should WordPress developers undertake when building themes or plugins?

Any developer at WisdmLabs would chime with Sumit’s response, for the same question. Making a plugin secure is a matter of following simple development practices. And an important practice would be to implement “nonce”.

Securing Form Submission Requests with Nonce – a One Time Token

Nonce- number used once – is an arbitrary number used only once. In WordPress it’s actually a hash generated and consists of numbers and letters. Using nonce is a security practice followed to prevent the misuse of URLs and forms.

sumit_pore_nonce
Sumit Pore in an Interview with WisdmLabs

A nonce is particularly used to secure your database. When a form request is being submitted, a one time token called nonce is generated. A nonce is generally included in a hidden HTML form field or as a part of a URL, and is sent along when a form is submitted, or a URL is clicked. Since it has to be a one-time-unique token, the nonce adds security and is verified before details are entered into the database.

The nonce security mechanism helps prevent unwanted repeated, expired or malicious form requests from being processed.

[space]

How to Use Nonce

As stated, you can add nonce to a URL or as a field in a form. You then need to verify it, once the URL is clicked or a form is submitted. Let’s find out how.

Adding Nonce to a URL

Using nonce in a URL helps you protect the URL from being submitted again. You have to get the current URL, and create a nonce URL as follows:

$wdm_url =  get_permalink();
$nonce_url = wp_nonce_url( $wdm_url, 'nonce_action_name' );

[space]

Adding Nonce as a Form Field

To add a nonce field in a form, you have to use the wp_nonce_field function

<form method="post">
      <?php wp_nonce_field( 'nonce_action_name', 'nonce_name' ); ?>
       <input type="submit" value="submit" name="Go">
</form>

[space]

Verifying Nonce without AJAX

Now, the nonce we generated can be verified using the wp_verify_nonce WordPress function on the wp hook. The below example, tells you how:

function wdm_verify_nonce()
{
   if(isset($_POST['Go']))
   {
       $wdm_retrieved_nonce = $_POST['nonce_name'];
       if(!wp_verify_nonce($wdm_retrieved_nonce, 'nonce_action_name'))
       {
           echo "Form cannot be submitted";
           die();
       }
}
add_action( 'wp', 'wdm_verify_nonce' );

[space]

Verifying Nonce with AJAX

With simple tweaks you can implement nonce via AJAX calls. In WordPress a nonce must be created in PHP. So in order to use it in your AJAX request you have pass it from your PHP code to your JavaScript code. The below code explains how this can be done:

Step #1: To begin with, let’s consider we’ve added nonce as a hidden form field

<?php
echo '<input type="hidden" name="wdm-ajax-nonce" id="wdm-ajax-nonce" value="' . wp_create_nonce( 'wdm-ajax-nonce' ) . '" />';
?>

Step #2: In your Javascript file, you have to add a security attribute.

<script type="text/javascript">
jQuery( document ).ready( function ( $ ) {
    var data = {
        action: 'wdm_my_action',
        security: $( '#wdm-ajax-nonce' ).val()
    };
    $.post( ajaxurl, data, function ( response ) {
        alert( "Response: " + response );
    } );
} );
</script>

Step #3: To verify the nonce via an AJAX request, we have to use the check_ajax_referer function on the wp_ajax_ action hook:

function wdm_verify_nonce_handler() {
    check_ajax_referer( 'nonce_action_name', 'security' );
    die;
}
add_action( 'wp_ajax_wdm_my_action', 'wdm_verify_nonce_handler' );

[space]

Your Thoughts

hugh_lashbrooke_security
Hugh Lashbrooke in an Interview with WisdmLabs

As a WordPress developer, making the plugin or theme you develop secure- should be your primary concern. The use of nonce is just one such security measure you should undertake. Be sure to watch this space for more such tips or tricks. Until then, if you have any questions, do make sure to direct them to me using the comment section below. :-)

Get a FREE Consultation

Let's build something that lasts.

Share what's on your mind — a clear brief, a half-formed idea, or just a sense that something needs to change. We'll listen first, ask the right questions, and point you toward what's actually worth building.

We take on a handful of projects each quarter,ones where we can truly make a difference.

  • Receive a human response within 24 hours
  • Get a detailed scope and quote upfront
  • We're happy to sign an NDA upon request

    Free 30-Min Strategy Call

    Your Name *

    Your Phone No *

    Work Email *

    Your Budget*

    Project Details *