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 = [];
    //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 -->
<?php } //end if not sent ?>

1 Answer 1


You could use the admin_post URL and actions to process form input and then redirect back to your page.

The form:

<form action="<?php echo admin_url('admin-post.php'); ?>" method="post">
  <input type="hidden" name="action" value="do_something">
  <input type="hidden" name="origin" value="<?php the_ID(); ?>">
  <input type="submit" value="Submit">

Then the action:

add_action( 'admin_post_do_something', 'wpd_do_something' );
add_action( 'admin_post_nopriv_do_something', 'wpd_do_something' );

function wpd_do_something() {
    // do something, then...
    wp_redirect( get_permalink( $_REQUEST['origin'] ) );
  • So, in wpd_do_something I validate the input and add errors to the $errors array - how do I pass this back to the original form to display these errors? Commented May 9, 2016 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.