I needed to run a couple functions when a WooCommerce order was deleted / trashed using the admin edit order screen.
I was looking for a specific WooCommerce hook, but then realized I just needed to use the default WordPress hook wp_trash_post
and check for the post type (i.e. shop_order
). Silly me.
‘wp_trash_post’ example snippet for WooCommerce
In this example, I’ll send a basic email notification every time an order is trashed.
wp_trash_post
provides one parameter: the post ID (i.e. order ID if we are just focusing on WooCommerce). You can use it to get other data from the order if needed.
add_action('wp_trash_post','order_trashed_send_email', 10, 1); function order_trashed_send_email ($order_id) { // 1. only continue if it is a WooCommerce order (i.e. 'shop_order') if( get_post_type($order_id) !== 'shop_order' ) return; // 2. get other data from order if needed $order = wc_get_order( $order_id ); $edit_order_url = $order->get_edit_order_url(); // 3. setup a basic email with wp_mail $to = "[email protected]"; $subject = "Order #$order_id was deleted"; $message = " <p>Hello,</p> <p>The order #$order_id was deleted.</p> <p><a href="$edit_order_url">View it here</a></p> "; $headers = "Content-type: text/html"; wp_mail( $to, $subject, $message, $headers ); }
That’s it! 🤓