WordPress: Are you sure you want to do this?

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.

Loading

Webmentions