Handle POST and GET requests in WordPress using admin-post.php

Today we are going to learn how to handle POST and GET requests in WordPress using custom functions and admin-post.php. There are various ways to process and handle POST requests in WordPress. You could use a page template or even a custom script. When using a custom script, you do not have access to WordPress or its functions by default. If you are using a page template, you jeopardise maintainability by mixing logic and display code. WordPress offers an elegant method for processing POST (or GET) requests using custom functions via admin-post.php.

In this example we will be processing POST data from a simple contact form submission. We first add the HTML for our form.

<form method="post" action="<?php admin_url( 'admin-post.php' )' ?>">
  <input type="hidden" name="action" value="process_form">
  <label for="name">Name:</label>
  <input type="text" name="name" id="name">
  <label for="email">Email:</label>
  <input type="text" name="email" id="email">
  <input type="submit" name="submit" value="Submit">
</form>

As mentioned earlier we will be processing the post request via admin-post.php. To get the URL for this script we use the WordPress function admin_url() and add it to our forms action attribute. The hidden input element will be used to hook into the admin-post.php script and our custom form processing function.

Next we will create a custom function for processing the form data and hook it into our form submission via the admin_post hook.

<?php
add_action( 'admin_post_nopriv_process_form', 'process_form_data' );
add_action( 'admin_post_process_form', 'process_form_data' );
function process_form_data() {
  // form processing code here
}
?>

We mentioned earlier that the hidden input element in our form would allow us to hook into admin_post. The first 2 lines above use the format admin_post_nopriv_$action and admin_post_$action respectively as the hook, where $action is the value of the hidden input in our form. The hidden input element must have action as the name attribute’s value for this to work.

admin_post_$action fires when a user is logged in and admin_post_nopriv_$action fires when a user is not logged in, which means you can create multiple custom functions to handle requests, depending on whether a user is logged in or not.

You will now have access to the form data via the $_POST (or $_GET) array(s) in your custom function(s). Once you have processed, validated or sanitised the form data you can redirect to a front-end page using wp_redirect.

Using this method to handle POST and GET requests in WordPress, when submitting a form, will prevent browsers from displaying a form re-submission warning when a user hits the back button after submission.

References