wc_reduce_stock_levels

Reduce stock levels for items within an order.

Description

wc_reduce_stock_levels( (int|WC_Order) $order_id ); 

Parameters (1)

0. $order_id (int|WC_Order)
The order id.

Usage

  1. if ( !function_exists( 'wc_reduce_stock_levels' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'woocommerce/includes/wc-stock-functions.php'; 
  3.  
  4. // The order id. 
  5. $order_id = null; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = wc_reduce_stock_levels($order_id); 
  9.  

Defined (1)

The function is defined in the following location(s).

/includes/wc-stock-functions.php  
  1. function wc_reduce_stock_levels( $order_id ) { 
  2. if ( is_a( $order_id, 'WC_Order' ) ) { 
  3. $order = $order_id; 
  4. $order_id = $order->get_id(); 
  5. } else { 
  6. $order = wc_get_order( $order_id ); 
  7. if ( 'yes' === get_option( 'woocommerce_manage_stock' ) && $order && apply_filters( 'woocommerce_can_reduce_order_stock', true, $order ) && sizeof( $order->get_items() ) > 0 ) { 
  8. foreach ( $order->get_items() as $item ) { 
  9. if ( $item->is_type( 'line_item' ) && ( $product = $item->get_product() ) && $product->managing_stock() ) { 
  10. $qty = apply_filters( 'woocommerce_order_item_quantity', $item->get_quantity(), $order, $item ); 
  11. $item_name = $product->get_formatted_name(); 
  12. $new_stock = wc_update_product_stock( $product, $qty, 'decrease' ); 
  13.  
  14. if ( ! is_wp_error( $new_stock ) ) { 
  15. /** translators: 1: item name 2: old stock quantity 3: new stock quantity */ 
  16. $order->add_order_note( sprintf( __( '%1$s stock reduced from %2$s to %3$s.', woocommerce ), $item_name, $new_stock + $qty, $new_stock ) ); 
  17.  
  18. // Get the latest product data. 
  19. $product = wc_get_product( $product->get_id() ); 
  20.  
  21. if ( '' !== get_option( 'woocommerce_notify_no_stock_amount' ) && $new_stock <= get_option( 'woocommerce_notify_no_stock_amount' ) ) { 
  22. do_action( 'woocommerce_no_stock', $product ); 
  23. } elseif ( '' !== get_option( 'woocommerce_notify_low_stock_amount' ) && $new_stock <= get_option( 'woocommerce_notify_low_stock_amount' ) ) { 
  24. do_action( 'woocommerce_low_stock', $product ); 
  25.  
  26. if ( $new_stock < 0 ) { 
  27. do_action( 'woocommerce_product_on_backorder', array( 'product' => $product, 'order_id' => $order_id, 'quantity' => $qty ) ); 
  28.  
  29. // ensure stock is marked as "reduced" in case payment complete or other stock actions are called 
  30. $order->get_data_store()->set_stock_reduced( $order_id, true ); 
  31.  
  32. do_action( 'woocommerce_reduce_order_stock', $order );