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.
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.
You have two choices:
functions.php
and do it in theinit
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
(Thisfunctions.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 useheader();
orwp_redirect();
here.