How to properly URL redirect in WordPress after form submission?

How do I properly redirect after a form submission in WordPress? I truly have searched for it all over the place and have not yet found an answer to this. I think a good explanation to this question might benefit many.

In my case, I have a form that submits to itself, if the form validates, the data is saved and the user should be redirected. In case it fails, the user should see an error or be redirected depending on the nature of the error.

Read More

After researching, the most proper way seems to be to use the function wp_redirect(), but I can’t get it to work. I know why, because the header has already been sent out ( meaning, browser has started to output and can’t redirect). I got that part. But then, how do I use this function properly? I can’t wrap my head around this one.

I tried using the good old header(Location: http://www.example.com/); response. No luck with that either.

Can anyone elaborate on this? Thanks.

Related posts

Leave a Reply

1 comment

  1. You have two choices:

    • Write your own plugin, and do the validation, and redirect from there if there was no error, or set the error if there was
    • Write it in the functions.php and do it in the init state.

    To write your own plugin, is a little bit more complicated, but not so hard, if you can programming.

    If you do not want to do this, you need to do something like this, in your functions.php (This functions.php is in your theme directory. If there is no file like this, just create one.

    Action on init is always happens, when all important wordpress files are loaded, but there was no output in the buffer, so you can use header(); or wp_redirect(); here.

    add_action('init', 'myInit');
    function myInit() {
        if (isset($_POST["mysubmit"])) {
            $errors = myFormValidation();
            if (empty($errors)) {
                //Do whatever you want here 
                header("Location: yoururl.php");
                die();
            }
            //Set the errors here
        }
    }
    
    function myFormValidation() {
        $errors = array();
        //do your validation here. check wordress documentation how to do this.
        return $errors;
    }