Last active
July 28, 2019 08:01
-
-
Save kish2011/dd21c1189b77fdcdd6f22d4466ac10ff to your computer and use it in GitHub Desktop.
WC Auto Restore Stock
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action( 'woocommerce_order_status_processing_to_cancelled', 'restore_order_stock', 10, 1 ); | |
add_action( 'woocommerce_order_status_completed_to_cancelled', 'restore_order_stock', 10, 1 ); | |
add_action( 'woocommerce_order_status_on-hold_to_cancelled', 'restore_order_stock', 10, 1 ); | |
add_action( 'woocommerce_order_status_processing_to_refunded', 'restore_order_stock', 10, 1 ); | |
add_action( 'woocommerce_order_status_completed_to_refunded', 'restore_order_stock', 10, 1 ); | |
add_action( 'woocommerce_order_status_on-hold_to_refunded', 'restore_order_stock', 10, 1 ); | |
function restore_order_stock( $order_id ) { | |
$order = new WC_Order( $order_id ); | |
if ( ! get_option('woocommerce_manage_stock') == 'yes' && ! sizeof( $order->get_items() ) > 0 ) { | |
return; | |
} | |
foreach ( $order->get_items() as $item ) { | |
if ( $item['product_id'] > 0 ) { | |
$_product = $order->get_product_from_item( $item ); | |
if ( $_product && $_product->exists() && $_product->managing_stock() ) { | |
$old_stock = $_product->stock; | |
$qty = apply_filters( 'woocommerce_order_item_quantity', $item['qty'], $this, $item ); | |
$new_quantity = $_product->increase_stock( $qty ); | |
do_action( 'woocommerce_auto_stock_restored', $_product, $item ); | |
$order->add_order_note( sprintf( __( 'Item #%s stock incremented from %s to %s.', 'woocommerce' ), $item['product_id'], $old_stock, $new_quantity) ); | |
$order->send_stock_notifications( $_product, $new_quantity, $item['qty'] ); | |
} | |
} | |
} | |
} // End restore_order_stock() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment