How to Create and Use Nonce in WordPress

Hello wordpress developer

In this tutorial i am going to discuss about wordpress nonce. In this following tutorial i will show you how we can create and use nonce in wordpress.

nonce is a "number used once" to help protect URLs and forms from certain types of misuse, malicious or otherwise. WordPress nonces aren't numbers, but are a hash made up of numbers and letters.

We need to use wordpress nonce to secured our requested data before submitting into database. It works like Laravel CSRF token protection for form data. Wordpress nonce provide a hidden field to protect our form data.

For CSRF attacks we need to create wordpress nonce for every post requested field. No need to create it for get request. See the example that how WordPress nonce works.

How To Use Nonce In A Form

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

 

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

Check Is Nonce Valid?

When you added nonce in a form, you have 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!');
}

 

Hope it can help you.