WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Plugin API/Action Reference/admin post (action)

This page is marked as incomplete. You can help Codex by expanding it.

Description

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_$youraction", where $youraction is your GET or POST request's 'action' parameter.

Usage

If you needed to create an 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 allows you to hook the above GET or POST requests.

add_action( 'admin_post_add_foobar', 'prefix_admin_add_foobar' );
//this next action version allows users not logged in to submit requests
add_action( 'admin_post_nopriv_add_foobar', 'prefix_admin_add_foobar' );

function prefix_admin_add_foobar() {
    status_header(200);
    die("Server received '{$_REQUEST['data']}' from your browser.");
    //request handlers should die() when they complete their task
}

Related