What is the real intention for admin-post.php?

admin-post.php is like a poor mans controller for handling requests.

It’s useful in the sense that you don’t need to process your request on an alternative hook such as init and check to see whether or not special keys exists on the superglobals, like:

function handle_request() {

    if ( !empty($_POST['action']) && $_POST['action'] === 'xyz' ) {
        //do business logic
    }

}

add_action('init', 'handle_request');

Instead using admin-post.php affords you the ability to specify a callback function that will always be called on any request that supplies an action value that matches the suffix supplied to the action.

function handle_request() {

    //do business logic here...

}

add_action( 'admin_post_handle_request', 'handle_request' );
add_action( 'admin_post_nopriv_handle_request', 'handle_request' );

In the above example, we can forgoe the need to check for !empty($_POST['action']) && $_POST['action'] === 'xyz' because at this point that processing has been taken care of for us.

That is the result of the specifying the action parameter and value and posting said value to the admin-post.php URL.

Additionally what is beneficial is that admin-post.php handles both $_POST and $_GET so it’s not neccessary to check what kind of method the request is of course unless you want to for more complex processing.

Bottom line:

It is safe to use, it’s just the name that throws you off.

By the way you should also remember to wp_redirect() the user back to an acceptable location as requesting admin-post.php will return nothing but a white screen as its response.

Leave a Comment