Advertisement
mixlife

Auto restore stock

Nov 26th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. if ( ! class_exists( 'WC_Auto_Stock_Restore' ) ) {
  2. class WC_Auto_Stock_Restore {
  3.  
  4. function __construct() {
  5. add_action( 'woocommerce_order_status_pending_to_failed', array( $this, 'restore_order_stock' ), 10, 1 );
  6. }
  7.  
  8. public function restore_order_stock( $order_id, $order ) {
  9. $items = $order->get_items();
  10.  
  11. if ( ! get_option('woocommerce_manage_stock') == 'yes' && ! count( $items ) > 0 )
  12. return; // We exit
  13.  
  14. foreach ( $order->get_items() as $item ) {
  15. $product_id = $item->get_product_id();
  16.  
  17. if ( $product_id > 0 ) {
  18. $product = $item->get_product();
  19.  
  20. if ( $product && $product->exists() && $product->managing_stock() ) {
  21.  
  22. // Get the product initial stock quantity (before update)
  23. $initial_stock = $product->get_stock_quantity();
  24.  
  25. $item_qty = apply_filters( 'woocommerce_order_item_quantity', $item->get_quantity(), $this, $item );
  26.  
  27. // Update the product stock quantity
  28. // Replace DEPRECATED methods: increase_stock() & discrease_stock()
  29. wc_update_product_stock( $product, $item_qty, 'increase' );
  30.  
  31. // Get the product updated stock quantity
  32. $updated_stock = $initial_stock + $item_qty;
  33.  
  34. do_action( 'woocommerce_auto_stock_restored', $product, $item );
  35.  
  36. // A unique Order note: Store each order note in an array…
  37. $order_note[] = sprintf( __( 'Product ID #%s stock incremented from %s to %s.', 'woocommerce' ), $product_id, $initial_stock, $updated_stock);
  38.  
  39. // DEPRECATED & NO LONGER NEEDED - can be removed
  40. //$order->send_stock_notifications( $product, $updated_stock, $item_qty );
  41.  
  42. }
  43. }
  44. }
  45. // Adding a unique composite order note (for multiple items)
  46. $order_notes = count($order_note) > 1 ? implode(' | ', $order_note) : $order_note[0];
  47. $order->add_order_note( $order_notes );
  48. }
  49. }
  50. $GLOBALS['wc_auto_stock_restore'] = new WC_Auto_Stock_Restore();
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement