How to redirect in WordPress after form submission

Dealing with forms in WordPress plugins sooner or later you’ll have to redirect the user on successful or failed submission. An example situation is that a user submits a form in your website, and you want to return some feedback based on the form data, eg “Fill more data” or “Successful submission”. One way to achieve that is to serialize the data and save it into Cookie, however if user does not accept cookies your data will not pass through. The solution I like is saving the data I want to pass in a transient and returning the id as a GET parameter, in that way you’re sure that the information will get delivered and WordPress will handle serialization/unserialization¬† if you store objects or arrays in the transient. Now a little code:

In this example after your form validation you want to return your feedback to the user and you’re doing that by:

  1. Create a signature from a random string of 5 characters
  2. Create a transient with that signature as a name and your object/array as value, setting the expiration for 10 minutes
  3. Using wp_redirect to redirect the user to the same url he came from but using add_query_arg you pass your signature as a GET parameter to the url

How to use that information in your template is fairly simple:

This is how you redirect user after form submission in WordPress and how to pass feedback from init hook to the front-end.

You can download the code for this how-to in
About Pavel Petrov 2 Articles |  18 How-tos
Pavel is a senior developer for the last 7 years, with extended interest in Linux administration, WordPress and Symfony.

Be the first to comment

Leave a Reply

Your email address will not be published.


*