public function calculate_shipping_for_package($package = array(), $package_key = 0)
{
if (!$this->enabled || empty($package) || !$this->is_package_shippable($package)) {
return false;
}
// Check if we need to recalculate shipping for this package
$package_to_hash = $package;
// Remove data objects so hashes are consistent
foreach ($package_to_hash['contents'] as $item_id => $item) {
unset($package_to_hash['contents'][$item_id]['data']);
}
$package_hash = 'wc_ship_' . md5(json_encode($package_to_hash) . WC_Cache_Helper::get_transient_version('shipping'));
$session_key = 'shipping_for_package_' . $package_key;
$stored_rates = WC()->session->get($session_key);
if (!is_array($stored_rates) || $package_hash !== $stored_rates['package_hash'] || 'yes' === get_option('woocommerce_shipping_debug_mode', 'no')) {
// Calculate shipping method rates
$package['rates'] = array();
foreach ($this->load_shipping_methods($package) as $shipping_method) {
// Shipping instances need an ID
if (!$shipping_method->supports('shipping-zones') || $shipping_method->get_instance_id()) {
$package['rates'] = $package['rates'] + $shipping_method->get_rates_for_package($package);
// + instead of array_merge maintains numeric keys
}
}
// Filter the calculated rates
$package['rates'] = apply_filters('woocommerce_package_rates', $package['rates'], $package);
// Store in session to avoid recalculation
WC()->session->set($session_key, array('package_hash' => $package_hash, 'rates' => $package['rates']));
} else {
$package['rates'] = $stored_rates['rates'];
}
return $package;
}