Last active
December 6, 2024 20:32
Custom inventory stock reduction in WooCommerce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php // For implementation instructions see: https://aceplugins.com/how-to-add-a-code-snippet/ | |
/** | |
* Reduce with custom stock quantity based on the settings. | |
* | |
* @param $quantity | |
* @param $order | |
* @param $item | |
* @return mixed | |
*/ | |
function ace_custom_stock_reduction( $quantity, $order, $item ) { | |
/** @var WC_Order_Item_Product $product */ | |
$multiplier = $item->get_product()->get_meta( '_stock_multiplier' ); | |
if ( empty( $multiplier ) && $item->get_product()->is_type( 'variation' ) ) { | |
$product = wc_get_product( $item->get_product()->get_parent_id() ); | |
$multiplier = $product->get_meta( '_stock_multiplier' ); | |
} | |
if ( ! empty( $multiplier ) ) { | |
$quantity = $multiplier * $quantity; | |
} | |
return $quantity; | |
} | |
add_filter( 'woocommerce_order_item_quantity', 'ace_custom_stock_reduction', 10, 3 ); | |
/** | |
* Order change stock reduction fix. | |
* | |
* @param $prevent | |
* @param $item | |
* @param $item_quantity | |
* @return bool|mixed | |
*/ | |
function ace_custom_stock_reduction_order_change( $prevent, $item, $item_quantity ) { | |
$stock_reduced = wc_stock_amount( $item->get_meta( '_reduced_stock', true ) ); | |
$stock_reduction = ace_custom_stock_reduction( $item->get_quantity(), null, $item ); | |
if ( $stock_reduction == $stock_reduced ) { | |
$prevent = true; | |
} | |
return $prevent; | |
} | |
add_filter( 'woocommerce_prevent_adjust_line_item_product_stock', 'ace_custom_stock_reduction_order_change', 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for your work. I'm happy to contribute back. I added on a bit so that the variations available were calculating correctly and disabling the add to cart button. I suspect you'll see issues with this add, but it was my first ever mod to WP, haven't used PHP in years, and didn't any any tools - just editing functions.php in the browser and hitting refresh.