Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shameemreza/20ac78e4e953d788aec9f12cc4f11ace to your computer and use it in GitHub Desktop.
Save shameemreza/20ac78e4e953d788aec9f12cc4f11ace to your computer and use it in GitHub Desktop.
Automatically Restock on Subscription Cancellation
add_action('woocommerce_subscription_status_cancelled', 'restock_inventory_on_subscripadd_action('woocommerce_subscription_status_cancelled', 'adjust_inventory_on_subscription_cancel', 10, 1);
function adjust_inventory_on_subscription_cancel($subscription) {
if (!$subscription) return;
foreach ($subscription->get_items() as $item) {
$product = $item->get_product();
if ($product && $product->managing_stock()) {
$current_stock = $product->get_stock_quantity();
$item_quantity = $item->get_quantity();
// Increase the stock by the quantity in the canceled subscription
$new_stock = $current_stock + $item_quantity;
$product->set_stock_quantity($new_stock);
$product->save();
}
}
}
@shameemreza
Copy link
Author

Updated a bit to make the code compatible with both variable and simple subscriptions:

add_action('woocommerce_subscription_status_cancelled', 'adjust_inventory_on_subscription_cancel', 10, 1);

function adjust_inventory_on_subscription_cancel($subscription) {
    if (!$subscription) return;

    foreach ($subscription->get_items() as $item) {
        $product = $item->get_product();
        $variation_id = $item->get_variation_id();

        // Ensure the product is variable and has stock management enabled
        if ($product && $product->managing_stock()) {
            $current_stock = $product->get_stock_quantity();
            $item_quantity = $item->get_quantity();

            // Adjust stock for the specific variation or parent product
            $new_stock = $current_stock + $item_quantity;

            if ($variation_id) {
                $variation = wc_get_product($variation_id);
                if ($variation && $variation->managing_stock()) {
                    $variation->set_stock_quantity($new_stock);
                    $variation->save();
                }
            } else {
                $product->set_stock_quantity($new_stock);
                $product->save();
            }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment