I have created a WooCommerce plugin that enables free shipping for subscribers. It seems to have broken following a recent WooCommerce upgrade.
Specifically, the problem seems that the shipping class of the cart items may not be being retrieved correctly.
Here is my calculate_shipping code - can anyone advise what is wrong?
/**
* Add free shipping option for customers in base country with an active subscription,
* but only if the cart doesn't contain an item with the 'heavy-item-shipping-class'.
*
* @access public
* @param mixed $package
* @return void
*/
public function calculate_shipping($package) {
global $woocommerce;
// Check country and subscription status
if (is_user_in_base_country() && does_user_have_active_subscription()) {
// This flag will be set to TRUE if cart contains heavy items
$disable_free_shipping = FALSE;
// Get cart items
$cart_items = $package['contents'];
// Check all cart items
foreach ($cart_items as $cart_item) {
// Get shipping class
$shipping_class = $cart_item['data']->shipping_class; // *** IS THIS THE RIGHT WAY TO GET THE SHIPPING CLASS ??? ***
// If heavy item, set flag so free shipping option is not made available
if ($shipping_class === 'heavy-item-shipping-class') {
// Set flag
$disable_free_shipping = TRUE;
// Enough
break;
}
}
// If appropriate, add the free shipping option
if ($disable_free_shipping === FALSE) {
// Create the new rate
$rate = array(
'id' => $this->id,
'label' => "Free Shipping",
'cost' => '0',
'taxes' => '',
'calc_tax' => 'per_order'
);
// Register the rate
$this->add_rate($rate);
}
else {
// Doesn't qualify for free shipping, so do nothing
}
}
}
UPDATE
I've looked at the %package
array and noticed that it now contains the shipping class under [shipping_class:protected]
. (Previously, this must have been [shipping_class]
.) Is it possible to extract this data? If not, what is the correct way of doing it?
calculate_shipping
function as a parameter. According to docs.woocommerce.com/wc-apidocs/class-WC_Shipping.html , it's a multi-dimensional array of cart items to calc shipping for. – ban-geoengineering