Skip to content

Instantly share code, notes, and snippets.

@MCKLtech
Created March 7, 2019 20:58
Show Gist options
  • Save MCKLtech/84f40976ee3028cfb0c01625bd4c4c12 to your computer and use it in GitHub Desktop.
Save MCKLtech/84f40976ee3028cfb0c01625bd4c4c12 to your computer and use it in GitHub Desktop.
HOWTO: Create a WordPress AJAX Endpoint for a JSON Payload
<?php
/*
* In this GIST, we register a webhook that will be available for other applications to call e.g. JSON
* This code could be added to functions.php or your own plugin.
*/
//Register an end point for logged in users
add_action("wp_ajax_my_webhook", "my_webhook");
//Register an end point for logged out users
add_action("wp_ajax_nopriv_my_webhook", "my_webhook");
/* This AJAX end point will be available at:
* https://www.domain.com/wp-admin/admin-ajax.php?action=my_webhook
*/
/* My function assumes we'll be recieving a JSON Payload */
function my_webhook () {
//Decode the incoming JSON Payload
$data = json_decode(file_get_contents('php://input'), true);
//Output to the log (For Debug, not mandatory)
error_log(print_r($data,true));
//Set up for scheduled event
$data = array($data);
//Set up a schedule event in 15 seconds to process the data. NEVER process synchronously!
wp_schedule_single_event( time()+15, 'do_json_processing', $data );
//Set a 200 (Success Header)
status_header(200);
/* Always die for AJAX */
die();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment