Skip to content

Instantly share code, notes, and snippets.

@iyut
Last active March 5, 2021 12:42
Show Gist options
  • Save iyut/f2b82b49055c0cc6dda4f933a4b0dcfd to your computer and use it in GitHub Desktop.
Save iyut/f2b82b49055c0cc6dda4f933a4b0dcfd to your computer and use it in GitHub Desktop.
Splitting the cart by quantity
function custom_split_shipping_packages_shipping_class( $packages ) {
// Reset all packages
$packages = array();
$split_package_qty = array();
foreach ( WC()->cart->get_cart() as $item_key => $item ) {
for( $i = 0; $i < $item['quantity']; $i++ ){
$new_item = $item;
$new_item['quantity'] = 1;
$item_arr = array(
$item_key => $new_item
);
$split_package_qty[] = $item_arr;
}
}
for( $i = 0; $i < count( $split_package_qty ); $i++ ){
$item_arr = $split_package_qty[$i];
$packages[] = array(
'contents' => $item_arr,
'contents_cost' => array_sum( wp_list_pluck( $item_arr, 'line_total' ) ),
'applied_coupons' => WC()->cart->get_applied_coupons(),
'user' => array(
'ID' => get_current_user_id(),
),
'destination' => array(
'country' => WC()->customer->get_shipping_country(),
'state' => WC()->customer->get_shipping_state(),
'postcode' => WC()->customer->get_shipping_postcode(),
'city' => WC()->customer->get_shipping_city(),
'address' => WC()->customer->get_shipping_address(),
'address_2' => WC()->customer->get_shipping_address_2()
)
);
}
return $packages;
}
add_filter( 'woocommerce_cart_shipping_packages', 'custom_split_shipping_packages_shipping_class' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment