From 75133c366a5a8e42b5934490278139de8eacff81 Mon Sep 17 00:00:00 2001 From: dwindown Date: Mon, 10 Nov 2025 16:06:15 +0700 Subject: [PATCH] fix(orders): Initialize WooCommerce cart/session before use MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Issue: 500 error on shipping/calculate and orders/preview endpoints Error: "Call to a member function empty_cart() on null" ## Root Cause: WC()->cart is not initialized in admin/REST API context Calling WC()->cart->empty_cart() fails when cart is null ## Solution: Initialize WooCommerce cart and session before using: ```php // Initialize if not already loaded if ( ! WC()->cart ) { wc_load_cart(); } if ( ! WC()->session ) { WC()->session = new \WC_Session_Handler(); WC()->session->init(); } // Now safe to use WC()->cart->empty_cart(); ``` ## Changes: - Added initialization in calculate_shipping() - Added initialization in preview_order() - Both methods now safely use WC()->cart ## Testing: - ✅ Endpoints no longer return 500 error - ✅ Cart operations work correctly - ✅ Session handling works in admin context --- includes/Api/OrdersController.php | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/includes/Api/OrdersController.php b/includes/Api/OrdersController.php index 24eb07b..39e7b90 100644 --- a/includes/Api/OrdersController.php +++ b/includes/Api/OrdersController.php @@ -1236,6 +1236,15 @@ class OrdersController { } try { + // Initialize WooCommerce cart and session if not already + if ( ! WC()->cart ) { + wc_load_cart(); + } + if ( ! WC()->session ) { + WC()->session = new \WC_Session_Handler(); + WC()->session->init(); + } + // Create a temporary cart to calculate shipping WC()->cart->empty_cart(); @@ -1319,6 +1328,15 @@ class OrdersController { } try { + // Initialize WooCommerce cart and session if not already + if ( ! WC()->cart ) { + wc_load_cart(); + } + if ( ! WC()->session ) { + WC()->session = new \WC_Session_Handler(); + WC()->session->init(); + } + // Use WooCommerce cart for calculation WC()->cart->empty_cart();