WordPress has a number of built-in functions designed to secure forms. You can find the list in the Functional Reference, but for convenience, I’ll also include it below.
In this (note to myself) I’m just listing the most basic way to secure a form on the front end. I’m writing little forms for clients all the time and this method of securing the form is simple and easy to implement.
There are two functions we’ll use and the first one appears within our form. It’s wp_nonce_field()
. All we’re going to do achieve some basic security is add an action and a name attribute like this:
<form name="secure_form" method="post" action="" > <?php wp_nonce_field('my_action_attr','my_name_attr'); ?> <input name="email" type="email" value="" /> <input name="submit" type="submit" value="submit" /> </form>
By including the nonce field in the form, we’ve now created a method by which we can verify whether the form was submitted from our page or not. In your code that processes the form submission, you’ll now want to do just that… verify the nonce referrer using wp_verify_nonce()
.
You’re probably already checking to see if the form was posted with something like if(!empty($_POST))
, so all you need to do is add verification of the nonce to that like this:
if( !empty($_POST) && wp_verify_nonce($_POST['my_name_attr'],'my_action_attr') ) { process_the_form(); } else { die(); }
That right there will prevent any processing of form data unless the requirements of the nonce field have been met.