WooCommerce待支付订单取消后无法自动补货问题求助
WooCommerce待支付订单取消后不自动补货问题的原因及解决方法
问题原因
- WooCommerce默认库存逻辑中,Pending(待支付)状态订单的库存扣减属于临时锁定,而非正式的库存扣减操作。当这类订单转为Cancelled(取消)时,系统默认不会触发库存回补流程,因为它判定这只是释放临时锁定的库存,而非恢复已正式扣减的库存。
- On Hold(待处理)、Processing(处理中)状态的订单属于正式扣减库存,因此取消时会触发标准的库存回补机制。
强制回补的自定义函数
可以通过添加以下代码,强制Pending状态订单取消后自动回补库存:
/** * 针对Pending转Cancelled状态的订单,强制回补库存 */ add_action('woocommerce_order_status_pending_to_cancelled', 'restore_stock_for_pending_cancelled', 10, 1); function restore_stock_for_pending_cancelled($order_id) { $order = wc_get_order($order_id); if (!$order) return; foreach ($order->get_items() as $item) { $product_id = $item->get_product_id(); $variation_id = $item->get_variation_id(); $quantity = $item->get_quantity(); // 执行库存回补 wc_update_product_stock($product_id, $quantity, 'increase', $variation_id); // 可选:添加库存变动日志 $target_product = wc_get_product($variation_id ?: $product_id); $target_product->add_stock_log( sprintf('订单 #%s(原Pending状态)取消,回补库存 %d', $order_id, $quantity), $quantity ); } }
使用说明
- 将代码添加到当前主题的
functions.php文件末尾,或通过Code Snippets等自定义代码插件添加。 - 操作前建议备份网站数据,避免意外问题。
- 代码仅针对「Pending转Cancelled」的状态变更触发回补,不会干扰其他订单状态的正常库存逻辑。
内容的提问来源于stack exchange,提问作者Somos Flow
相关产品推荐
相关产品推荐

