I have a shortcode which generates a simple contact form. The form posts back to the same page where its processed, validated and sent via email. All works well, however refreshing the page resubmits the form.
I understand I need a post/redirect/get pattern to prevent this, but can't figure out how to implement this with Wordpress - what should the action
be? Can someone provide a simple example?
$errors = [];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//check and validate POST variables
...
// add errors to $errors array
...
// check if form considered spam
if(empty($errors) && !$spam) {
$sent = wp_mail($to, $subject, $message, $headers);
if($sent) {
$success = true;
$_POST = array();
}
} // end if no errors
echo "<pre>".print_r($_POST, true)."</pre>";
} //end if POST
//loop through errors (if any) and display accordingly
...
// display success message if $success
...
<?php if( !$sent) { //hide form if successfully sent ?>
<form id="contact_form" action="" method="post">
<!-- form inputs -->
</form>
<?php } //end if not sent ?>