drkskwlkr icon

Rebalance stock qtys between two products

drkskwlkr | PRO | 06/03/24 10:58:29 AM UTC | 0 ⭐ | 928 👁️ | Never ⏰ | []
PHP |

1.55 KB

|

Source Code

|

0 👍

/

0 👎

add_action( 'woocommerce_reduce_order_stock', function( $order ) {
    // The IDs below are the product IDs for the 2 products I used to test the snippet
    // DO NOT FORGET to change them to the proper product IDs for your installation!!!
    // ALWAYS ALWAYS ALWAYS test on a staging site first.
    $pack_1_id = 1991;
    $pack_6_id = 1990;
 
    // Check if stock adjustment has already been run for this order to prevent recursion
    if ( get_post_meta( $order->get_id(), '_stock_rebalanced', true ) ) {
        return;
    }
 
    foreach ( $order->get_items() as $item ) {
        $product_id = $item->get_product_id();
        $qty_bought = $item->get_quantity();
 
        if ( $product_id == $pack_6_id ) {            // Directly reduce the 1-pack stock by 6 times the quantity of 6-packs sold.
            $pack_1 = wc_get_product( $pack_1_id );
            $pack_1_new_stock = $pack_1->get_stock_quantity() - ( $qty_bought * 6 );
            wc_update_product_stock( $pack_1, $pack_1_new_stock, 'set' );
        }
    }
 
    // Now, recalculate and adjust the stock for the 6-pack based on the remaining 1-pack stock.
    $pack_1 = wc_get_product( $pack_1_id );
    $current_pack_1_stock = $pack_1->get_stock_quantity();
    $new_pack_6_stock = intdiv( $current_pack_1_stock, 6 );
 
    $pack_6 = wc_get_product( $pack_6_id );
    wc_update_product_stock( $pack_6, $new_pack_6_stock, 'set' );
 
    update_post_meta( $order->get_id(), '_stock_rebalanced', 'yes' );       // Mark as stock rebalanced to prevent future recursion on this order
}, 10, 1 );

Comments