See also wp_ajax__requestaction on the new WordPress Developer Resources.
This hook allows you to handle your custom AJAX endpoints. The wp_ajax_ hooks follows the format "wp_ajax_$youraction"
, where $youraction is the 'action'
field submitted to admin-ajax.php.
If you need to create an AJAX handler for an "add_foobar" request, you would create a hook like this:
add_action( 'wp_ajax_foobar', 'my_ajax_foobar_handler' ); function my_ajax_foobar_handler() { // Make your response and echo it. // Don't forget to stop execution afterward. wp_die(); }
The following code is an example using jQuery that would trigger the above hook.
jQuery.post( my_foobar_client.ajaxurl, { 'action': 'foobar', 'foobar_id': 123 }, function(response) { console.log('The server responded: ', response); } );
Note: The foobar_id
would be available in your PHP hook handler via $_POST['foobar_id']
.
For more information, see Ajax Plugin Handbook on the new WordPress Developer Resource.
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_, like this: add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );.
To allow both, you must register both hooks!