Using WordPress nonces

Wordpress NoncesNonces are an important security feature of WordPress. Whilst they’re not infallible, they should be used on all forms you submit in WordPress (backend, frontend, plugins etc.).

The term ‘nonce’ stands for ‘number used once’. As it happens they’re often used more than once in WordPress but that doesn’t detract from they’re usefulness as a security feature.

They’re simple to use so there’s no excuse for not doing so.

Let’s say you have a form as follows:

<form action="" method="post" name="myform">
<input name="mytextfield" type="text" value="Hello" />
<input name="submit" type="submit" value="Submit" />
</form>

In order to add a nonce field to the form, you just need to add a line thus:

<form action="" method="post" name="myform">
<?php wp_nonce_field('my_form_submit'); ?>
<input name="mytextfield" type="text" value="Hello" />
<input name="submit" type="submit" value="Submit" />
</form>

You can pass whatever name parameter you like (I’ve just used ‘my_form_submit’ above) but it’s probably best to make the name unique to every form you use.

Now, when you handle the for submission you need to check the nonce field:


<?php
$nonce = $_REQUEST['_wpnonce'];
if (!wp_verify_nonce($nonce, 'my_form_submit')) {
wp_die('Security error');
}
?>

And that’s basically it. Use the same name for the second parameter of wp_verify_nonce that you used in the wp_nonce_field in the form. This will ensure that the results you get from the form actually came from the form you submitted. It’s not a complete security solution but it’s one way to help ensure form results aren’t spoofed.

Leave a Reply