I lost an hour to this problem, so I’m blogging it to hopefully help others.
I’m experimenting with the WP Webhooks plugin for helping me solve a problem with sites that I manage.1 Webhooks are a simple technology that lets a “request” to a specific URL that then completes some other action. That request contains details about the specific instance of the request.
In my case, I need to watch for an error on one WordPress site and then send an email from a different WordPress site to notify me of the issue. Why a different site? I can’t count on other sites to reliably send emails, so I’m using a site I control to increase my control over the email sending.
Now, I knew how to send a request from WordPress when I needed to, but it surprisingly took me way too long to find the documentation about how to send the webhook request to the WP Webhooks plugin. This is probably because WP Webhooks mostly assumes you’re using a 3rd-party service to send the webhook. And further, as long as you’re on a WordPress site, there’s a much shorter way to do it than what they show.
The part I got stuck on was figuring out what format WP Webhooks was expecting for the body of the request. I tried variations on JSON and multipart forms before I realized in their example that they were using a URL query string.
Here’s the code that I finally got to work:
<?php
add_action( '{wordpress_action_to_trigger_webhook}', __NAMESPACE__ . '\send_webhook_request' );
/**
* Send request to webhook set up with WP Webhooks plugin
*/
function send_webhook_request() {
$url = '{YOUR WEBHOOK URL}';
$data = array(
'body' => http_build_query( array(
'action' => 'send_email',
'send_to' => 'email@example.com',
'subject' => '{Email Subject}',
'message' => '{Email message}'
) )
);
wp_remote_post( $url, $data );
}You’ll need to customize this to specify the action or actions that trigger the request, and you may need a conditional check inside your function depending on the context. This example sends an email with the send_email action I was using, but this will work for any WP Webhooks action.
- Shoutout to Patty at Carkeek Studios for telling me about this plugin! ↩︎