WC_Cart::get_shipping_packages
Get packages to calculate shipping for.
This lets us calculate costs for carts that are shipped to multiple locations.
Shipping methods are responsible for looping through these packages.
By default we pass the cart itself as a package - plugins can change this. through the filter and break it up.
Method of the class: WC_Cart{}
Hooks from the method
Returns
Array. of cart items
Usage
$WC_Cart = new WC_Cart(); $WC_Cart->get_shipping_packages();
Changelog
| Since 1.5.4 | Introduced. |
WC_Cart::get_shipping_packages() WC Cart::get shipping packages code WC 10.7.0
public function get_shipping_packages() {
/**
* Filters the shipping packages for the cart.
*
* @since 1.5.4
* @param array $packages The shipping packages.
* @return array The shipping packages.
*/
$shipping_packages = apply_filters(
'woocommerce_cart_shipping_packages',
array(
array(
'contents' => $this->get_items_needing_shipping(),
'contents_cost' => array_sum( wp_list_pluck( $this->get_items_needing_shipping(), 'line_total' ) ),
'applied_coupons' => $this->get_applied_coupons(),
'user' => array(
'ID' => get_current_user_id(),
),
'destination' => array(
'country' => $this->get_customer()->get_shipping_country(),
'state' => $this->get_customer()->get_shipping_state(),
'postcode' => $this->get_customer()->get_shipping_postcode(),
'city' => $this->get_customer()->get_shipping_city(),
'address' => $this->get_customer()->get_shipping_address(), // This is an alias of address_1, provided for backwards compatibility.
'address_1' => $this->get_customer()->get_shipping_address_1(),
'address_2' => $this->get_customer()->get_shipping_address_2(),
),
'cart_subtotal' => $this->get_displayed_subtotal(),
),
)
);
// Return empty array if invalid object supplied by the filter or no packages.
if ( ! is_array( $shipping_packages ) || empty( $shipping_packages ) ) {
return array();
}
// Remove any invalid packages before adding package IDs.
$shipping_packages = array_filter(
$shipping_packages,
function ( $package ) {
return ! empty( $package ) && is_array( $package );
}
);
// Add package ID and package name to each package after the filter is applied.
$index = 1;
foreach ( $shipping_packages as $key => $package ) {
$shipping_packages[ $key ]['package_id'] = $package['package_id'] ?? $key;
$shipping_packages[ $key ]['package_name'] = $this->get_shipping_package_name( $shipping_packages[ $key ], $index, count( $shipping_packages ) );
++$index;
}
return $shipping_packages;
}