While writing a plug-in for WordPress recently I came across a very strange error message:
Are you sure you want to do this?
Now my initial reaction was “Well yes, I do want to do this!”. Unfortunately that wasn’t an option. It just told me to try again… same message… ad nauseam. What I was actually trying to do was pass some form information from the plug-in dashboard panel to the plug-in tables in the database.
After searching the web for a while and not having much luck I decided to ‘view source’ on the Quickpress widget which was doing a similar function. I noticed these two hidden inputs:
1 2 | <input type="hidden" id="_wpnonce" name="_wpnonce" value="[random code here]" /> <input type="hidden" name="_wp_http_referer" value="/wp-admin/" /> |
After a brief search in google about ‘Cryptographic nonce‘ it occurred to me that’s what was missing. A vital security feature that WordPress uses to validate that the form information came from the current site rather than an external source. Very clever, but quite frustrating if you don’t know about it.
Adding the following to the form code fixed the issue.
1 2 3 4 5 | $content = '<form name="formname" method="post" action="'.$url.'">'; if (function_exists('wp_nonce_field')){ $content .= wp_nonce_field('hidden_input_name_here'); } $content .= '...'; |
Simple when you know about it! The ‘wp_nonce_field‘ function is documented in the WordPress codex.
Update: Just to make it a bit clearer I added the code to the plug-in file that was generating my form. So for example:
1 2 3 4 5 6 7 8 | <form name="our_form" method="post" action="http://oururl.com/action"> <?php if (function_exists('wp_nonce_field')){ $content .= wp_nonce_field('hidden_input_name_here'); } ?> <!-- Other relevent code for the generated form --> </form> |
The hidden inputs are inserted into the form allowing WordPress to validate where the request came from.
vinayak on February 8 10 / 38 Permalink
Adding the following to the form code fixed the issue.
Adding the following to where?Which location?Which file?Where to add?
Simply saying adding the following to the form.Can you make it a bit more clear?
Matt on February 8 10 / 38 Permalink
Hi Vinayak,
I’ve added a slight update to the post which will hopefully make it a little clearer. It’s added to the plug-in file that is generating the form; it may be that you are receiving the error for a different reason. It isn’t the most helpful error message.
William on April 13 10 / 102 Permalink
And of course out in the non-geek community, the word ‘Nonce’ is a slang term for a pervert or sex-offender.
WP_Nonce, anyone?
Hmmm. For a second there I thought there must be a joker at WP writing code…
Elvis on July 10 10 / 190 Permalink
Hi,
In my case the issue was the specific plugin that one “Google Analytics 3 codes for WordPress”, when I disabled it, everything is back to normal.
I hope help someone