How to use WordPress Nonce

Whats 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 which should use during development to avoid CSRF(cross-site request forgery) attacks.

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

How To Use Nonce In A Form

As mentioned, 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 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 nonce in a form, you need to check whether passing 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 website through URLs also. In addition, for sensitive pages nonce plays important role. Lets say we have settings page on website which contains some sensitive data which should be protected. We want to prevent it from CSRF attacks as well. So i create nonce URL for setting page by 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 following way. Here also we are using wp_verify_nonce() function to check nonce validity. I will add below code at the top of settings page.

if ( isset($_GET['setting-nonce']) && wp_verify_nonce($_GET['setting-nonce'], 'page-settings') ) {
	//safe tp 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.