I have a page template having a form which further have 3 input fields and and a submit button. I have a written a function in a plugin which inserts the retrieved values in database. I am trying to figure out what to write in action attribute of the form, so that when user clicks the submit button, the function gets executed?
2 Answers
Output The Form
Can be done via Shortcode API.
What Should Be Set on Form Action
Leave it blank <form action="">
. Make sure you avoid using reserved name as form field name like name
or p
. Otherwise your form submission will hit 404
.
How Can We Validate or Process The Form?
Hook into template_redirect
.
add_action( 'template_redirect', 'wpse149613_form_process' );
function wpse149613_form_process(){
if(!isset($_POST['submit'])) // assuming you're using POST and submit button name is 'submit'
return;
// Validate the form, verify nonce
// process form
}
Hope it makes sense. This is how I usually handle form submission.
-
1It has cleared lot of doubts. Will try to implement the same and mark this question closed once done. :) Jun 14, 2014 at 12:01
Here's another post! that can help you.
Basically you need to specify admin_url( 'admin-post.php' )
as the action for the form and place a hidden input specifying a custom action.
Then you can register that action in your plugin so you can process the form information.
Example:
<form action="<?=admin_url( 'admin-post.php' ) ?>" method="POST">
<!-- your inputs -->
<input type="hidden" name="action" value="myplugin_mycustomaction"/>
<input type="submit" value="Send"/>
</form>
Then in your PHP plugin can place the function that process that form this way
add_action( 'admin_post_nopriv_myplugin_mycustomaction',array( "class_that_owns_that_function", 'yourmethod' ) );
public function yourmethod()
{
// Do what you want with $_POST variables
}
If the method is in the same class you can use $this instead of the name of owns the function.