Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrease product total sales count from cancelled WooCommerce Orders

I'm displaying the total sales using get_total_sales() WC_Product method, in a product table of my WooCommerce store.

However this number doesn't get updated after an user cancel its order, it keeps adding sales.

Anybody can show me how to change this get_total_sales formula, to be able to remove the canceled ordered numbers in the total sales?

like image 513
Mauro Garcia Avatar asked Jun 29 '26 20:06

Mauro Garcia


1 Answers

You are right, the related product total sales doesn't decrease when a paid order (from processing or complete status) is cancelled in WooCommerce 3+…

For info, Paid orders includes "processing" and "completed" order statuses.

The following will decrease the product total sales when a paid order is cancelled by a Customer, a Shop manager or an Administrator:

add_action( 'woocommerce_order_status_changed', 'update_product_total_sales_on_cancelled_orders', 10, 4 );
function update_product_total_sales_on_cancelled_orders( $order_id, $old_status, $new_status, $order ){
    if ( in_array( $old_status, array('processing', 'completed') ) && 'cancelled' === $new_status
    && ! $order->get_meta('_order_is_canceled') ) {

        // Loop through order items
        foreach ( $order->get_items() as $item ) {
            // Get the WC_product object (and for product variation, the parent variable product)
            $product = $item->get_variation_id() > 0 ? wc_get_product( $item->get_product_id() ) : $item->get_product();

            $total_sales   = (int) $product->get_total_sales(); // get product total sales
            $item_quantity = (int) $item->get_quantity(); // Get order item quantity

            $product->set_total_sales( $total_sales - $item_quantity ); // Decrease product total sales
            $product->save(); // save to database
        }
        $order->update_meta_data('_order_is_canceled', '1'); // Flag the order as been cancelled to avoid repetitions
        $order->save(); // save to database
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

like image 195
LoicTheAztec Avatar answered Jul 02 '26 13:07

LoicTheAztec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!