2

If I submit a form with an action of /wp-admin/admin-post.php, is there a way to return form errors to the originating page?

My form has an input with the action set:

<input name="action" value="enquiry_form" />

I have an actions setup to manage the validation:

add_action('admin_post_enquiry_form', 'mytheme_enquiry_form_submit');

I can return to the original form page with a wp_redirect:

wp_redirect('/contact/');

But how can I pass variables/ messages back to this page after redirecting?

UPDATE: To add clarification, I was under the impression this was the "correct" way to handle form data, rather than simply adding an init hoot to check for a specific POST variable. There are countless tutorials where people use the admin-post.php action, for example:

WPMUDEV Handling Form Submissions

AdaptiveWeb Handle POST and GET requests in WordPress

SitePoint Handling POST Requests the WordPress Way

3
  • 1
    You shouldn't be submitting frontend forms that lead to files for the admin area, especially if you're undoing the security restrictions so logged out users can do it. You should instead ask how to handle a form on the frontend, and how to create posts in code
    – Tom J Nowell
    Nov 8, 2017 at 19:25
  • 1
    So why are there admin_post and admin_post_nopriv actions if not for logged-in and logged-out users? I thought forms should always use this so that actions could be setup correctly? I can easily (and securely) handle the field validation, and am fine handling POST data if the form submits back to itself. I was under the impression using my initial method was the "right" way to do things? Nov 8, 2017 at 20:11
  • hmmm admin-post.php doesn't do what I thought it did, eitherway it's rare you'll see it in plugins, and a lot of security restrictions that can be made don't account for it at all. Usually the page that renders the form also handles it, so you leave the action empty, this way all your form code is in one place. Also look into the REST API instead of using Admin AJAX
    – Tom J Nowell
    Nov 8, 2017 at 20:52

2 Answers 2

1

You can send GET variables in the URL using wp_redirect. For example:

wp_redirect( home_url() .'/form?result=error&reason=3');

As far as I know, yes, admin-post is the best-practices way to handle POST data in WordPress.

1
0

Rather than stuffing all the validation error descriptions in the URL, you could use Transients (very easy to use). Then, in your redirect URL you could just add a transientRef={whatever} parameter.

I am using Transients to store a WP_Error object that holds the validation error descriptions.

Makes for a much cleaner solution.

Your Answer

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

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