I am trying to put together a WordPress plugin that will send a webhook when a plugin is updated.
I am hooking into upgrader_process_complete, and also tried upgrader_post_install but nothing seems to be working. There is no errors showing in the logs either.
Here is the plugin code:
// Webhook URL
define('WEBHOOK_URL', 'https://example.com');
// Hook into the plugin update process
add_filter('upgrader_post_install', 'webhook_on_plugin_update', 10, 3);
function webhook_on_plugin_update($response, $hook_extra, $result) {
// Check if the update process is for a plugin
if ($hook_extra['type'] === 'plugin' && $hook_extra['action'] === 'update') {
// Get the updated plugin information
$plugin_info = $hook_extra['plugins'][0];
// Prepare data for the webhook payload
$payload = array(
'event' => 'plugin_updated',
'plugin_name' => $plugin_info['Name'],
'plugin_version' => $plugin_info['Version'],
'timestamp' => current_time('timestamp'),
);
// Send the webhook
send_webhook_request($payload);
}
return $response;
}
function send_webhook_request($payload) {
// Use wp_remote_post to send the webhook request
wp_remote_post(WEBHOOK_URL, array(
'body' => json_encode($payload),
'headers' => array('Content-Type' => 'application/json'),
));
}
Does anyone have any insights into hooking into the upgrader_post_install or upgrader_process_complete actions that would be helpful.
EDITED to add code with action
define('WEBHOOK_URL', 'https://example.com');
add_action('upgrader_process_complete', 'webhook_on_plugin_update', 150);
function webhook_on_plugin_update($upgrader_object, $options) {
if ($options['type'] === 'plugin' && $options['action'] === 'update') {
$plugin_info = get_plugin_data(WP_PLUGIN_DIR . '/' . $options['plugins'][0]);
$payload = array(
'event' => 'plugin_updated',
'plugin_name' => $plugin_info['Name'],
'plugin_version' => $plugin_info['Version'],
'timestamp' => current_time('timestamp'),
);
send_webhook_request($payload);
}
}
function send_webhook_request($payload) {
wp_remote_post(WEBHOOK_URL, array(
'body' => json_encode($payload),
'headers' => array('Content-Type' => 'application/json'),
));
}
So, after taking a look at some other plugins and how they did it, I took a lead from the Activity Log plugin and after a few attempts I came up with this, which is working.
This is was was received by the webhook
and this is what showed in the logs
This is the code from Activity Log which I looked at to try and figure it out.
Having looked back through the logs to see what errors my old code was spitting out, I found this which was telling me there was an issue with the number of arguments being passed to the webhook_on_plugin_update function. It would seem only one argument was being passed to the upgrader_process_complete action.
Thank you to those who replied, I do appreciate the time you took out of your day to reply to my query.