Triggering WordPress AJAX Callback from PHP

WordPress makes it easy to run PHP code from Javascript. This is extremely useful for running custom code without reloading the page. The following part I’m using to send backup snapshot emails.

jQuery(".anchor_commands input.button").click(function(e){

  var data = {
    'action': 'snapshot_email',
    'post_id': form.post_id,
    'email': form.email
  };

  // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
  jQuery.post(ajaxurl, data, function(response) {
    jQuery('.install-result').html( response );
  });

  e.preventDefault();

});

This will run the PHP function snapshot_email_action_callback.

// Fetch Backblaze link for snapshot and sends email
add_action( 'wp_ajax_snapshot_email', 'snapshot_email_action_callback' );

function snapshot_email_action_callback() {
	global $wpdb; // this is how you get access to the database

	// Variables from JS request
	$snapshot_id = intval( $_POST['snapshot_id'] );
	$email       = $_POST['email'];
	$name        = get_field( 'name', $snapshot_id );
	$url         = anchor_generate_b2_download_link( $snapshot_id );

	$to      = $email;
	$subject = "Anchor Hosting - Snapshot #$snapshot_id";
	$body    = "Snapshot #${snapshot_id} for ${domain}. Expires after 1 week.<br /><br /><a href='${url}'>Download Snapshot</a>";
	$headers = array( 'Content-Type: text/html; charset=UTF-8' );

	wp_mail( $to, $subject, $body, $headers );

	wp_die(); // this is required to terminate immediately and return a proper response
}

This works great when using jQuery, however recently I was wondering if it’s possible to trigger from WP-CLI shell or another PHP function. While it’s possible to have PHP make a web request it’s complex and unnecessary. I discovered you can simply reset the $_POST variable and trigger the PHP callback function directly like this.

// If email found then manually trigger download link
if ( $email ) {
	$_POST = array(
		'email'       => $email,
		'snapshot_id' => $snapshot_id,
	);
	snapshot_email_action_callback();
}