Forms in WordPress (nonfiction)
This article documents the use of HTML forms in WordPress.
Handling Form Submissions in WordPress with Admin-Post and Admin-Ajax
This section includes excerpts from Handling Form Submissions in WordPress with Admin-Post and Admin-Ajax by Karan NA Gupta.
Form Submissions with admin-post.php in WordPress
The form submission is made to the admin-post.php using the admin_url( 'admin-post.php' ) function rather than hardcoding the URL. When WordPress receives the form, it will look for the value of the action field to trigger the form hooks. In my case, it will generate the admin_post_nds_form_response hook. Had it been a page open to the public view, it would have triggered the admin_post_nopriv_nds_form_response hook.
The Form Handler for the POST request
At this stage, if you submit the form, you’ll be redirected to an empty page with the page URL set to the admin-post.php. This is because there is no form handler to process the request yet. To process the request, I registered my custom handler the_form_response in the define_admin_hooks() method of class-init.php like this: $this->loader->add_action( 'admin_post_nds_form_response', $plugin_admin, 'the_form_response');
If you were using procedural code you would simply do add_action( 'admin_post_nds_form_response', 'the_form_response');
the_form_response() is where I’ll have full access to the form data via the $_POST or $_GET superglobals. As shown below, I added a breakpoint to the callback in my IDE to be certain that the hook would work as expected.
Form Validation and Input Sanitization
Before performing any operations, you must validate the nonce and sanitize the user input properly. I made use of the wp_verify_nonce( $nonce_name, $nonce_action ) function to verify the nonce, and sanitize_key() and sanitize_text_field() functions to sanitize the user input available in the $_POST variable. If the nonce verification fails, the user will get an error message as the server response, using the wp_die() WordPress function.
Note: I accessed the form data using the $_POST variable. Had I submitted the form using the get method, I would instead make use of the $_GET or $_REQUEST global variable.
Submitting the Server Response
After performing the server operations, it’s important to send the server response back to the user. To do this, you will first need to redirect the user back to an admin page or one that provides some feedback. I redirected the user back to the plugin page and used WordPress admin notices to display the server feedback. The server response in my example simply outputs the $_POST variable as a WordPress admin notice.
Form Submissions with AJAX (admin-ajax.php)
TO_DO ...