Advertisement
drkskwlkr

Rebalance stock qtys between two products

Jun 3rd, 2024
455
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.55 KB | Source Code | 0 0
  1. add_action( 'woocommerce_reduce_order_stock', function( $order ) {
  2.     // The IDs below are the product IDs for the 2 products I used to test the snippet
  3.     // DO NOT FORGET to change them to the proper product IDs for your installation!!!
  4.     // ALWAYS ALWAYS ALWAYS test on a staging site first.
  5.     $pack_1_id = 1991;
  6.     $pack_6_id = 1990;
  7.  
  8.     // Check if stock adjustment has already been run for this order to prevent recursion
  9.     if ( get_post_meta( $order->get_id(), '_stock_rebalanced', true ) ) {
  10.         return;
  11.     }
  12.  
  13.     foreach ( $order->get_items() as $item ) {
  14.         $product_id = $item->get_product_id();
  15.         $qty_bought = $item->get_quantity();
  16.  
  17.         if ( $product_id == $pack_6_id ) {            // Directly reduce the 1-pack stock by 6 times the quantity of 6-packs sold.
  18.             $pack_1 = wc_get_product( $pack_1_id );
  19.             $pack_1_new_stock = $pack_1->get_stock_quantity() - ( $qty_bought * 6 );
  20.             wc_update_product_stock( $pack_1, $pack_1_new_stock, 'set' );
  21.         }
  22.     }
  23.  
  24.     // Now, recalculate and adjust the stock for the 6-pack based on the remaining 1-pack stock.
  25.     $pack_1 = wc_get_product( $pack_1_id );
  26.     $current_pack_1_stock = $pack_1->get_stock_quantity();
  27.     $new_pack_6_stock = intdiv( $current_pack_1_stock, 6 );
  28.  
  29.     $pack_6 = wc_get_product( $pack_6_id );
  30.     wc_update_product_stock( $pack_6, $new_pack_6_stock, 'set' );
  31.  
  32.     update_post_meta( $order->get_id(), '_stock_rebalanced', 'yes' );       // Mark as stock rebalanced to prevent future recursion on this order
  33. }, 10, 1 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement