do_action( "wp_ajax_{$action}" )
Fires authenticated Ajax actions for logged-in users.
Description
The dynamic portion of the hook name, $action
, refers to the name of the Ajax action callback being fired.
More Information
- This hook allows you to handle your custom AJAX endpoints. The
wp_ajax_
hooks follows the format “wp_ajax_$action
“, where$action
is the ‘action
‘ field submitted toadmin-ajax.php
. - This hook only fires for logged-in users. If your action only allows Ajax requests to come from users not logged-in, you need to instead use wp_ajax_nopriv_$action such as:
add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );
. To allow both, you must register both hooks! - See also wp_ajax__requestaction
- See also Ajax Plugin Handbook
Source
File: wp-admin/admin-ajax.php
.
View all references
do_action( "wp_ajax_{$action}" );
Changelog
Version | Description |
---|---|
2.1.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.
Example migrated from Codex:
If you need to create an AJAX handler for an “
add_foobar
” request, you would create a hook like this:The following code is an example using jQuery that would trigger the above hook.
Note: The
foobar_id
would be available in your PHP hook handler via$_POST['foobar_id']
.Top ↑
Feedback
In jQuery.post example provided, ‘my_foobar_client.ajaxurl’ should be: ‘my_foobar_client.ajax_url’ — By Stringman —
using wp_send_json() to output your result as a json format
Top ↑
Feedback
For the sake of cleaner & more concise code: There is no need for
wp_die()
when usingwp_send_json()
. — By Sam Hayman —wp_die()
is not needed here, sincewp_send_json()
already makes awp_die()
— By Samy RABIH —