Last active
October 26, 2016 22:54
-
-
Save arelthia/78e52d6ea39a1cddd194 to your computer and use it in GitHub Desktop.
Woocommerce: Different shipping methods for different products in single cart
This file contains 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
/** Seperate freepromo products from other Items - forcing multiple carts **/ | |
add_filter( 'woocommerce_cart_shipping_packages', 'ps_two_shipping_methods_in_cart' ); | |
function ps_two_shipping_methods_in_cart( $packages ) { | |
$packages = array(); | |
$freepromo_items = array(); | |
$regular_items = array(); | |
$freeshipclass= 'freepromo'; | |
$shipto = 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() | |
); | |
// Sort freepromo from regular | |
foreach ( WC()->cart->get_cart() as $item ) { | |
if ( $item['data']->needs_shipping() ) { | |
if ( $item['data']->get_shipping_class() == $freeshipclass ) { | |
$freepromo_items[] = $item; | |
} else { | |
$regular_items[] = $item; | |
} | |
} | |
} | |
//If product qualifies for free shipping | |
if ( $freepromo_items && WC()->customer->get_shipping_country() =='US' ) { | |
$packages[] = array( | |
'ship_via' => array( 'free_shipping' ), | |
'contents' => $freepromo_items, | |
'contents_cost' => array_sum( wp_list_pluck( $freepromo_items, 'line_total' ) ), | |
'applied_coupons' => WC()->cart->applied_coupons, | |
'destination' => $shipto | |
); | |
}elseif ( $freepromo_items ) { //if product does qualify for free shipping but customer is not in US | |
$packages[] = array( | |
'ship_via' => array( 'usps','ups' ), //available shipping methods for international | |
'contents' => $freepromo_items, | |
'contents_cost' => array_sum( wp_list_pluck( $freepromo_items, 'line_total' ) ), | |
'applied_coupons' => WC()->cart->applied_coupons, | |
'destination' => $shipto | |
); | |
} | |
//If product does not qualify for free shipping | |
if ( $regular_items ) { | |
$packages[] = array( | |
'ship_via' => array( 'usps','ups' ), | |
'contents' => $regular_items, | |
'contents_cost' => array_sum( wp_list_pluck( $regular_items, 'line_total' ) ), | |
'applied_coupons' => WC()->cart->applied_coupons, | |
'destination' => $shipto | |
); | |
} | |
return $packages; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome, very helpful!