admin_post_{$action} WordPress Action Hook
The admin_post_{$action} hook is called whenever a user attempts to perform an action on a post in the WordPress admin. It is useful for performing custom validation or for taking action before the default handler is invoked.
do_action( "admin_post_{$action}" ) #
Fires on an authenticated admin post request for the given action.
Description
The dynamic portion of the hook name, $action
, refers to the given request action.
More Information
This hook allows you to create custom handlers for your own custom GET and POST requests. The admin_post_
hook follows the format “admin_post_$action
“, where $action
is your GET or POST request’s ‘action
‘ parameter.
Usage:
If you needed to create a request or form handler for an “add_foobar
” action request, you would create a hook like this:
add_action( 'admin_post_add_foobar', 'prefix_admin_add_foobar' ); function prefix_admin_add_foobar() { // Handle request then generate response using echo or leaving PHP and using HTML }
Using the above example, any time a GET or POST request is sent to WordPress, and the request’s ‘action
‘ parameter is set to ‘add_foobar
‘, this hook will be automatically executed. For example, the following HTML content would execute the above hook when the user clicks either Submit.
<a href="http://www.example.com/wp-admin/admin-post.php?action=add_foobar&data=foobarid">Submit</a>
<form action="http://www.example.com/wp-admin/admin-post.php" method="post">
<input type="hidden" name="action" value="add_foobar">
<input type="hidden" name="data" value="foobarid">
<input type="submit" value="Submit">
</form>
Note: The data value (foobarid
) would be available in your hook function from the $_GET
, $_POST
or $_REQUEST
array as is applicable.
Example:
This following example allows you to hook the GET or POST requests from the above html.
add_action( 'admin_post_add_foobar', 'prefix_admin_add_foobar' ); //this next action version allows users not logged in to submit requests //if you want to have both logged in and not logged in users submitting, you have to add both actions! add_action( 'admin_post_nopriv_add_foobar', 'prefix_admin_add_foobar' ); function prefix_admin_add_foobar() { status_header(200); //request handlers should exit() when they complete their task exit("Server received '{$_REQUEST['data']}' from your browser."); }
Source
File: wp-admin/admin-post.php
Changelog
Version | Description |
---|---|
2.6.0 | Introduced. |