Update stock with php
-
This is a bit of custom work so I don’t expect the dev to answer, maybe the community? Thanks for any help I could receive.
In my Woocommerce store, products are set as simple, but I use WS Form to add attributes to the product/order.
https://dev.biancoviaggi.com/viaggio/viaggio-a-medjugorje-in-pullman-il-29-03-2024/We sell travels packages. When a user purchase a product, the quantity decrease to 1. But if they’re a group of 4 travelers, the correct approach for our use case should be to decrease the stock of 4 (total number of people partecipating).
I tried this snippet that althought it correctly updates the stock quantity on purchase, it makes the wrong calculation:
add_action('woocommerce_checkout_order_processed', 'adjust_stock_based_on_travelers_checkout', 10, 1); function adjust_stock_based_on_travelers_checkout($order_id) { $order = wc_get_order($order_id); foreach ($order->get_items() as $item_id => $item) { // Passeggeri totali means "Total passengers" $passenger_total = wc_get_order_item_meta($item_id, 'Passeggeri totali', true); $passenger_total = intval($passenger_total); if ($passenger_total > 0) { $product = $item->get_product(); if ($product && $product->managing_stock()) { // Correctly decrease the stock $new_stock = wc_update_product_stock($product, $passenger_total * -1, 'decrease'); } } } }
I’m not sure where I found this similar approach that I applied, but probably there’s a better way to start this
- The topic ‘Update stock with php’ is closed to new replies.