Skip to content

Instantly share code, notes, and snippets.

@renjith-ph
Last active December 19, 2018 11:51
Show Gist options
  • Save renjith-ph/2ca6e8777b850b2e450fe4d8d8d21cc7 to your computer and use it in GitHub Desktop.
Save renjith-ph/2ca6e8777b850b2e450fe4d8d8d21cc7 to your computer and use it in GitHub Desktop.
Split cart packages based on product category. PluginHive Plugins : https://www.pluginhive.com/plugins/
/**
* Split cart packages based on product category.
* Created at : 17 Dec 2018
* Updated at : 19 Dec 2018
* PluginHive Plugins : https://www.pluginhive.com/plugins/
*/
add_filter( 'woocommerce_cart_shipping_packages', 'wf_split_cart_by_shipping_class_group' );
function wf_split_cart_by_shipping_class_group($package){
//Reset packages
$packages = array();
//Init splitted package
$splitted_packages = array();
// Group of category ids
$category_groups = array(
'cat1' => array(18), //category name => category ids
);
// group items by shipping classes
foreach ( WC()->cart->get_cart() as $item_key => $item ) {
if ( $item['data']->needs_shipping() ) {
$belongs_to_category = 'others'; // name if not in any group
$terms_post = get_the_terms( $item['product_id'] , 'product_cat' );
foreach ($terms_post as $term_cat) {
$term_cat_id = $term_cat->term_id;
foreach($category_groups as $class_group_key => $class_group){
if(in_array($term_cat_id, $class_group)){
$belongs_to_category = $class_group_key;
break;
}
}
}
$splitted_packages[$belongs_to_category][$item_key] = $item;
}
}
// Add grouped items as packages
if(is_array($splitted_packages)){
foreach($splitted_packages as $key => $splitted_package_items){
$packages[] = array(
'contents' => $splitted_package_items,
'package_name' => $key,
'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()
)
);
}
$package=$packages;
}
return $package;
}
add_filter( 'woocommerce_shipping_package_name','package_name', 10, 3 );
function package_name( $package_name, $iteration, $package ) {
if(isset($package['package_name']))
{
$package_name=$package['package_name'];
$product_names=array();
if ( count( $package ) > 1 ) {
foreach ( $package['contents'] as $item_id => $values ) {
$product_names[ $item_id ] = $values['data']->get_name() . ' ×' . $values['quantity'];
}
}
foreach ($package as $key => $value) {
}
unset($package['package_name']);
return $package_name.'<br>'.implode( ', ', $product_names );
}
return $package_name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment