Created
July 11, 2017 06:09
-
-
Save aliciaiceland/d3e221241ea2681c7c802312b98e9bbe to your computer and use it in GitHub Desktop.
Split cart by shipping classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_filter( 'woocommerce_cart_shipping_packages', 'split_cart_by_shipping_class' ); | |
function split_cart_by_shipping_class($packages){ | |
$packages = array(); | |
$new_packages = array(); | |
// Group of shipping class | |
$class_groups = array( | |
'group1' => array('heavy'), | |
'group2' => array('light'), | |
); | |
// Group cart items by shipping classes | |
foreach ( WC()->cart->get_cart() as $item_key => $item ) { | |
if ( $item['data']->needs_shipping() ) { | |
$belongs_to_class_group = 'none'; | |
$item_ship_class_id = $item['data']->get_shipping_class(); | |
if($item_ship_class_id){ | |
foreach($class_groups as $class_group_key => $class_group){ | |
if(in_array($item_ship_class_id, $class_group)){ | |
$belongs_to_class_group = $class_group_key; | |
continue; | |
} | |
} | |
} | |
$new_packages[$belongs_to_class_group][$item_key] = $item; | |
} | |
} | |
// Add grouped items as packages | |
if(is_array($new_packages)){ | |
foreach($new_packages as $splitted_package_items){ | |
$packages[] = array( | |
'contents' => $splitted_package_items, | |
'contents_cost' => array_sum( wp_list_pluck( $splitted_package_items, '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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment