WooCommerce技术需求:动态调整购物车中预售商品价格
Solution for Pre-Order with Free Pre-Ordered Quantity
Got it, let's work through your WooCommerce requirement: enabling pre-orders where customers don't get charged for the portion that's not in stock. We'll adjust the cart subtotal dynamically so only the available inventory is billed, and any quantity beyond that (the pre-order part) is free.
Complete Working Code Snippet
add_filter( 'woocommerce_cart_product_subtotal', 'modify_cart_product_subtotal_for_preorder', 10, 4 ); function modify_cart_product_subtotal_for_preorder( $product_subtotal, $product, $quantity, $cart ) { // Grab the current available stock quantity of the product $stock_qty = $product->get_stock_quantity(); // Check if we're in a pre-order scenario: stock is 0 OR cart quantity exceeds available stock if ( $stock_qty <= 0 || $quantity > $stock_qty ) { // Calculate how much of the order should actually be charged (only in-stock amount, or 0 if out of stock) $chargeable_qty = max( $stock_qty, 0 ); // Compute the new subtotal using WooCommerce's built-in price formatting $new_subtotal = wc_price( $chargeable_qty * $product->get_price() ); // Return the adjusted subtotal return $new_subtotal; } // If no pre-order is needed, keep the original subtotal return $product_subtotal; }
Breakdown of How This Works
- Trigger Logic: The code kicks in when either the product is completely out of stock (
$stock_qty <= 0) or the customer is trying to buy more units than are available. - Chargeable Quantity: We only bill for the number of units that are actually in stock. If the product is out of stock entirely, the chargeable quantity drops to 0 (so the customer pays nothing for that item's pre-order).
- Consistent Formatting: Using
wc_price()ensures the adjusted subtotal matches your store's currency settings and formatting rules, so there's no mismatch with other cart values. - Fallback: For regular orders where quantity doesn't exceed stock, everything stays as it normally would.
Quick Tips
- Double-check that stock management is enabled for your products in WooCommerce settings—this ensures
get_stock_quantity()returns accurate numbers. - If you want to add a clear note in the cart about the pre-ordered portion (like "2 units pre-ordered, free of charge"), you can extend this code or use the
woocommerce_cart_item_namefilter to add custom text for affected items.
内容的提问来源于stack exchange,提问作者Tasos
相关产品推荐
相关产品推荐

