fix(orders): Initialize WooCommerce cart/session before use
## 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
This commit is contained in:
@@ -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();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user