Skip to content

Instantly share code, notes, and snippets.

@neilgee
Last active October 6, 2022 13:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neilgee/5f60654d2583895e154729384cb51331 to your computer and use it in GitHub Desktop.
Save neilgee/5f60654d2583895e154729384cb51331 to your computer and use it in GitHub Desktop.
WooCommerce Webhook Custom Action Hook
<?php
/**
* Plugin Name: Woo Custom Webhook
* Plugin URI: https://wpbeaches.com/send-full-product-details-over-woocommerce-webhook-action-hook/
* Description: Custom WooCommerce Webhook Action
* Author URI: https://github.com/woocommerce/woocommerce/issues/20336#issuecomment-829510702
* Version: 0.1.0
*/
/**
* Set the proper resource payload for a custom action webhook
*
* @param int $target_webhook_id
* @param string $desired_resource 'order', 'product', 'coupon', or 'customer'
*/
function set_resource_for_webhook_payload_by_webhook_id($target_webhook_id, $desired_resource) {
// Set the desired_resource payload for this webhook ('order', 'product', 'coupon', 'customer')
add_filter('woocommerce_webhook_resource', function($resource, $webhook_id) use ($target_webhook_id, $desired_resource) {
if($webhook_id == $target_webhook_id) {
return $desired_resource;
}
return $resource;
}, 10, 2);
// Need to ensure our event (i.e., action) is seen as valid, as we've changed the default 'action.' prefix for the topic above
add_filter('woocommerce_valid_webhook_events', function($valid_events) use ($target_webhook_id) {
try {
$topic = wc_get_webhook($target_webhook_id)->get_topic();
list($resource, $event) = explode('.', $topic);
if(!empty($event)) {
$valid_events[] = $event;
}
return $valid_events;
} catch (Exception $e) {
return $valid_events;
}
}, 10);
}
// Change the Webhook ID to suit and data source of order, product, coupon or customer
add_action('init', function(){
set_resource_for_webhook_payload_by_webhook_id( 1, 'order' );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment