How to use a simple nonce in WordPress


Nonces are something I don’t see nearly enough in WP themes and plugins, it’s simple to implement since WP handles all the hard stuff and there are several functions and hooks ready to use.

What’s a nonce ? Nonces are used for security purposes to protect against unexpected or duplicate requests especially when using forms to submit data. Nonces basically prevent CSRF attacks (Cross-site request forgery) since each nonce is unique to the logged in user.

You can read more about them here:

A simple example: you have a theme admin page with a form that processes data when “submit”.

The first thing you need is to add a hidden nonce field to the form, something like:

<form action="<?php echo admin_url( '/your-theme-settings-page'); ?>" method="post">
<input class='button-primary' type='submit' name="foo" value='bar'>
<?php wp_nonce_field('my_nonce_action','my_nonce_field'); ?>

Now the nonce data will be available via $_POST when the form is submit.

If the page which outputs your results is the same as the page with your form (you can instead have it load another page and remove the first condition which is actually more normal) you can do the following:

 if(isset($_POST['foo'])) { 
     if ( !empty($_POST['foo']) && check_admin_referer( 'my_nonce_action', 'my_nonce_field' )){
         // you're output
         wp_die('Security check fail'); 

First we check isset($_POST['foo']) since we do not want to run anything if the form has not been submitted. If the form has been submitted we check if it is not empty and then we check for a valid nonce using check_admin_refererIf the check fails we use wp_die to output an error onto the page.

That’s it:)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s