wordpress form action submit

2019-02-07 07:24发布

问题:

have an own customized form in wordpress.

action=<?php bloginfo('template_url'); ?>/send_form.php"

on submit, it goes always to send_form.php but this php is for sending the info - and i cant style with with the theme....

is there a way to stay on the current page while it sends the info and print out and message in a field that the form has been sended succesfully???

anyone have some suggestion for me?

回答1:

The answer to this is quite involved and getting it right takes a little care, but here are the essential points of one approach:

  1. The action must be set to load the current page and you can do this by changing the action attribute in the <form> tag to: action=""
  2. In the template file for this page, detect when the page loads after a form submission. You can do this by checking the state of the $_POST variable.
  3. If there are post variables, process the form submission in the template file. You need to look at what happens in "send_form.php" to figure out what to do. Take care that you don't introduce security issues (e.g. be sure to use the NONCE).
  4. Redirect back to the same page to get rid of the post variables. If you don't do this people will get those "Do you want to resubmit the form" warning messages. See the PHP header() function for doing the redirect and note that this must happen before any output is sent to the page.
  5. Use server sessions to display a "Form submission successful". Set a session variable to your message before the redirect, then detect it when the page loads, display it, and remove it so the message doesn't display the next time the page loads.

That should give you a starting point.

If anyone else has a simpler solution, I'd love to hear it too.



回答2:

If you want to do it through plugin instead of the theme, then use "admin_post"(admin_post_YOUR_ACTION) and "admin_post_nopriv" (admin_post_nopriv_YOUR_ACTION) actions. (Btw, you can use those actions through theme also)

Here is a good explanation: https://www.sitepoint.com/handling-post-requests-the-wordpress-way/