How to use WordPress Nonce

What Is WordPress Nonce?

As mentioned in WordPress Codex, A WordPress nonce is a “number used once” to help protect URLs and forms from certain types of misuse, malicious or otherwise.

A nonce is nothing but a security token that should use during development to avoid CSRF(cross-site request forgery) attacks.

While developing a theme or plugin nonce should be used in a form or in a URL. As a WordPress developer, using Nonce is a good practice.

How To Use Nonce In A Form

As mentioned, a nonce is a token to prevent CSRF attacks. While dealing with forms, we should add this nonce in our forms. To add a nonce in a form we use a hidden field.

<input type="hidden" name="FIELD_NAME" value="<?php echo wp_create_nonce('NONCE_NAME'); ?>"

In the above code, replace the FIELD_NAME & NONCE_NAME with anything you want.

Check Is Nonce Valid?

Once you added a nonce in a form, you need to check whether passing the nonce is valid or not after form submission. WordPress provides a function wp_verify_nonce to check nonce validity.

if ( wp_verify_nonce( $_REQUEST['FIELD_NAME'], 'NONCE_NAME' ) ) {
    //safe to proceed
} else {
    die('Security Check!');
}

How To Use Nonce In URL

CSRF attacks can occur on websites through URLs also. In addition, for sensitive pages, nonce plays an important role. Let’s say we have a settings page on the website that contains some sensitive data which should be protected. We want to prevent CSRF attacks as well. So I create a nonce URL for the setting page in the following way.

<a href="<?php echo wp_nonce_url(get_bloginfo('url').'/settings', 'page-settings', 'setting-nonce'); ?>"></a>

Check Is Nonce Valid?

Now, we need to verify whether passing nonce is valid or not. We can do this in the following way. Here also we are using the wp_verify_nonce() function to check nonce validity. I will add the below code at the top of the settings page.

if ( isset($_GET['setting-nonce']) && wp_verify_nonce($_GET['setting-nonce'], 'page-settings') ) {
    //safe to proceed
}

I hope you understand how to use WordPress Nonce. If have any questions or suggestions please leave a comment below.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *