Changing shipping options in WooCommerce based on Cart and Coupon


/* Change shipping based on total cost purchased and or applied coupons are excluded. */
add_filter( 'woocommerce_shipping_packages', 'hide_flat_rate_if_cart_total_is_greater_than_threshold', 5, 1 );
function hide_flat_rate_if_cart_total_is_greater_than_threshold( $packages ) {
    $threshold1 = 249;
    $applied_coupons = WC()->session->get( 'applied_coupons', array() );
    $amount = WC()->cart->cart_contents_total;
    $availableRates = $packages[0]['rates'];
    $excluded_coupons = array('coupon1', 'coupon2', 'coupon3', 'coupon4', 'coupon5', 'coupon6', 'cooupon7', 'eight', 'nine', 'ten');

    $isExcludedCoupon = false;
    $map = array_map(function($c) use($excluded_coupons, &$isExcludedCoupon ){
        if( in_array($c, $excluded_coupons) ){
            $isExcludedCoupon = true;
        }
        return $c;
    }, $applied_coupons);

    $flatRateKey = '';
    array_map(function($r) use($availableRates, &$flatRateKey){
        $id = $r->get_id();
        $pos = substr_count($id, 'flat_rate');

        if($pos == 1 ){
            $flatRateKey = $id;
        }

        return $r;
    }, $availableRates);

    if ( $amount > $threshold1 && !$isExcludedCoupon) {
        unset($packages[0]['rates'][$flatRateKey]);
    }

    if ($isExcludedCoupon) {
        unset($packages[0]['rates']['woodiscountfree']);
        unset($packages[0]['rates']['free_shipping:2']);
    }

    return $packages;
}