Woocommerce 3特定订单状态变更自动补货实现及代码排错
Hey there! Let’s fix that auto-restock functionality for WooCommerce 3—sounds like you hit some syntax snags on lines 14 and 22, so I’ll walk you through a clean, working solution and point out common pitfalls that might’ve caused those errors.
Core Approach
We’ll use WooCommerce’s built-in woocommerce_order_status_changed hook, which fires whenever an order’s status updates. We’ll check if the new status is one we care about (like cancelled or refunded), then loop through the order’s items to restore their stock levels.
Working Code Snippet
/** * Auto-restock product inventory when order status changes to specific statuses */ add_action( 'woocommerce_order_status_changed', 'auto_restock_on_order_status_change', 10, 4 ); function auto_restock_on_order_status_change( $order_id, $old_status, $new_status, $order ) { // Define which statuses trigger restock (adjust these to your needs) $trigger_statuses = array( 'cancelled', 'refunded' ); // Exit early if the new status isn't a trigger if ( ! in_array( $new_status, $trigger_statuses ) ) { return; } // Loop through each item in the order foreach ( $order->get_items() as $item_id => $item ) { $product = $item->get_product(); // Skip non-stockable products (virtual, downloadable, etc.) if ( ! $product || ! $product->is_type( array( 'simple', 'variable' ) ) ) { continue; } // Calculate and update stock quantity $restock_quantity = $item->get_quantity(); $current_stock = $product->get_stock_quantity(); $new_stock = $current_stock + $restock_quantity; $product->set_stock_quantity( $new_stock ); $product->save(); // Add an order note for transparency (optional but helpful) $order->add_order_note( sprintf( 'Restocked %d units of "%s" — order status updated to %s.', $restock_quantity, $product->get_name(), $new_status ) ); } }
Why Your Original Code Might’ve Thrown Errors
Looking at lines 14 and 22 (common trouble spots here), these are likely culprits:
- Incorrect hook parameters: If you didn’t specify the 4 parameters (
10, 4) when adding the action, the$orderobject or status variables would be undefined. - Missing parentheses/syntax: Forgetting to close an
ifstatement bracket, or misspelling WooCommerce methods (like writingget_productinstead ofget_product()). - Outdated functions: Using legacy WooCommerce 2.x functions (like
$order->get_items( 'line_item' )instead of$order->get_items()) which don’t work in WooCommerce 3+.
How to Use This
- Copy the code above.
- Paste it into your child theme’s
functions.phpfile (or a custom plugin—never edit core WooCommerce files!). - Adjust the
$trigger_statusesarray to match the statuses that should trigger restock (e.g., add'failed'if needed).
This snippet is fully compatible with WooCommerce 3+ and handles edge cases like non-stockable products automatically.
内容的提问来源于stack exchange,提问作者Daniel Romagnoli

