Get list of Webhooks from Woocommerce

∥☆過路亽.° 提交于 2021-01-29 05:16:02

问题


I have built a Wordpress plugin that among other things, creates several Woocommerce Webhooks upon activation. This is done using internal API classes and functions, as per below:

function createWebhook($userID,$topic,$secret,$deliveryURL,$status)
{
    $webhook = new WC_Webhook();
    $webhook->set_user_id($userID); // User ID used while generating the webhook payload.
    $webhook->set_topic( $topic ); // Event used to trigger a webhook.
    $webhook->set_secret( $secret ); // Secret to validate webhook when received.
    $webhook->set_delivery_url( $deliveryURL ); // URL where webhook should be sent.
    $webhook->set_status( $status ); // Webhook status.
    $save = $webhook->save();
    return $save;
}

This works well.

What I want to be able to do is remove these Webhooks upon deactivation of the plugin. Is there any way to fetch the Woocommerce Webhooks via the internal Wordpress or Woocommerce API, so I can loop through and remove the relevant ones?

I would just remove all Webhooks where the delivery URL has a domain of xyz.com. This part is straight-forward, I just don't know how to fetch the Webhooks.

I don't want to use the external Woocommerce API, which requires an API key and HTTP requests.

Thanks


回答1:


I ended up querying the database to get the webhooks, which looks to be working well. I'm not sure there's any other way. Please let me know if there is!

    global $wpdb;
    $results = $wpdb->get_results( "SELECT webhook_id, delivery_url FROM {$wpdb->prefix}wc_webhooks" );
    foreach($results as $result)
    {
        if(strpos($result->delivery_url, 'domain.com') !== false)
        {
            $wh = new WC_Webhook();
            $wh->set_id($result->webhook_id);
            $wh->delete();
        }
    }



回答2:


You can get an array of all webhook IDs with the following:

$data_store = WC_Data_Store::load( 'webhook' );
$webhooks   = $data_store->search_webhooks();

That's what WooCommerce does when building the table list:

https://github.com/woocommerce/woocommerce/blob/master/includes/admin/class-wc-admin-webhooks-table-list.php



来源:https://stackoverflow.com/questions/52642092/get-list-of-webhooks-from-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!