user1 user1 - 5 months ago 74
PHP Question

Woocommerce order delete hook callback is not being called

I'm trying to hook a function to the order deletion (when permanently delete is clicked from admin page) but for some reason the function isn't called. My code looks something like

add_action('woocommerce_before_delete_order_item', function($id) {
$order = new WC_Order($id);
//do some stuff with order meta data
}, 10, 1);


I tried to throw and exception inside the function but no error occurred. Can somebody help?

Answer

The woocommerce_before_delete_order_item action runs every time an item is deleted from an order, not every time an order is deleted. You need to use the before_delete_post hook:

add_action('before_delete_post', function($id) {
    global $post_type;

    if($post_type !== 'shop_order') {
        return;
    }

    $order = new WC_Order($id);
    //do some stuff with order meta data
}, 10, 1);