WordPress redirect after successful form validation and submit

I have a custom page template with a form in page-report.php.

I do validation on it, so I need the action to lead to the same form, but I need to redirect to a different page on successful validation.

Read More

wp_redirect() is not working, because is spitting out the header() function after the output was started already.

if($_POST['report'])
{
    if($validator->ValidateForm())
    {
        wp_redirect('http://thankyou') // redirect
    }
}

I cannot use ob_start() and ob_flush() because the header is not included in this page template.

I tried to put a function in functions.php :

add_action('get_header','redirect_to');
function redirect_to($page){
    if($page)
    {   
        wp_redirect('http://www.google.com');
    }
}

But that works only if I don’t have the conditional if().

If I use it, the wp_redirect() is being spat out after the output was started.

What is my best approach to do this?
Thanks.

Related posts

Leave a Reply

4 comments

  1. I think you have to use the save_post hook:

    do_action(‘save_post’, ‘custom_add_save’);

    function custom_add_save($postID){
    // called after a post or page is saved
        if($_POST['report']) {
    
          if($validator->ValidateForm())
               {
                    wp_redirect('http://thankyou') // redirect
               }
    
        }
    

    Also you could just try using a plugin instead of your own code…Gravity Forms and Contact form 7 both work well.

    }

  2. I got it…
    Since I was doing everything from inside an admin page, the header was fired up before the wp_redirect() as it was explained in the question.

    So I ended up making a new function at the top:

    add_action('admin_init','redirect_to');
    function redirect_to()
    {
            if ( isset($_REQUEST['action']) && 'adduser' == $_REQUEST['action'] ) {
                        wp_redirect($redirect);
                        die();
                    }
            }
    
    }
    

    That is making sure that the redirect_to() function will be fired up before the header (on admin_init). Maybe not the most elegant solution, but it works perfect.