If Shipping Cost is Greater Than X, Apply Coupon Code

Viewed 47

Currently, our store offers "Free Shipping up to $350", after thought on how to incorporate this into eCom - I believe this will be the simplest method. Fetch Shipping Cost --> IF Shipping Costs > $350 --> Apply "350-shipping" coupon code.

We use 2 different plugins to calculate shipping:

1.) WooCommerce FedEx Shipping

2.) WooCommerce WWE LTL Quotes

Looking to incorporate this inside of functions.php. Note, I am also working on a solution, so will apply here if I get to it sooner

Notice here the correct code for the Shipping Page: https://i.imgur.com/TndLiHT.png

So far I have the following:

// $350 Shipping Coupon
add_filter( 'woocommerce_package_rates', 'custom_shipping_rate_label_based_on_cost', 100, 2 );
function custom_shipping_rate_label_based_on_cost( $rates, $package ){
 
    // Loop through available shipping rates
    foreach ( $rates as $rate_key => $rate ) {
      
            $rate_cost = $rate->cost;
            
            if ( $rate_cost > 350 ) {
                 echo "<script type='text/javascript'>alert('350 Detected');</script>";
            } 
        }
    return $rates;
}

What is missing here is I need to say:

IF ALL Items in Foreach are greater than $350. Right now, if I run this script, I get an endless loop of "350 detected"

1 Answers
add_action( 'woocommerce_after_calculate_totals', 'apply_coupon_depending_on_shipping_total', 999, 1 );
function apply_coupon_depending_on_shipping_total( $cart ) {    
    $coupon_code = 'coupon_code';
    
    if ( $cart->has_discount( $coupon_code ) ) {
        return;
    }
    
    $shipping_total = $cart->get_shipping_total();
    
    if ( $shipping_total > 350 ) {
        $cart->apply_coupon( $coupon_code );    
    }
}
Related