Check Cart Amount and Applied Coupons…


  1. /* Change shipping based on total cost purchased and or applied coupons are excluded. */
  2. add_filter( 'woocommerce_shipping_packages', 'hide_flat_rate_if_cart_total_is_greater_than_threshold', 5, 1 );
  3. function hide_flat_rate_if_cart_total_is_greater_than_threshold( $packages ) {
  4. $threshold1 = 249;
  5. $applied_coupons = WC()->session->get( 'applied_coupons', array() );
  6. $amount = WC()->cart->cart_contents_total;
  7. $availableRates = $packages[0]['rates'];
  8. $excluded_coupons = array('coupon1', 'coupon2', 'coupon3', 'coupon4', 'coupon5', 'coupon6', 'cooupon7', 'eight', 'nine', 'ten');
  9.  
  10. $isExcludedCoupon = false;
  11. $map = array_map(function($c) use($excluded_coupons, &$isExcludedCoupon ){
  12. if( in_array($c, $excluded_coupons) ){
  13. $isExcludedCoupon = true;
  14. }
  15. return $c;
  16. }, $applied_coupons);
  17.  
  18. $flatRateKey = '';
  19. array_map(function($r) use($availableRates, &$flatRateKey){
  20. $id = $r->get_id();
  21. $pos = substr_count($id, 'flat_rate');
  22.  
  23. if($pos == 1 ){
  24. $flatRateKey = $id;
  25. }
  26.  
  27. return $r;
  28. }, $availableRates);
  29.  
  30. if ( $amount > $threshold1 && !$isExcludedCoupon) {
  31. unset($packages[0]['rates'][$flatRateKey]);
  32. }
  33.  
  34. if ($isExcludedCoupon) {
  35. unset($packages[0]['rates']['woodiscountfree']);
  36. unset($packages[0]['rates']['free_shipping:2']);
  37. }
  38.  
  39. return $packages;
  40. }