Skip to content
Advertisement

Disable free shipping for specific coupon codes in WooCommerce

I am trying to remove the free shipping option in Woocommerce when someone uses a specific coupon code. I found this question which is very relevant to my question. The answer bellow seems really close to what I am looking for. I am new to php and trying to figure out where I would add an id for the coupon code I want to exclude.

add_filter( 'woocommerce_shipping_packages', function( $packages ) {
  $applied_coupons = WC()->session->get('applied_coupons', array());

  if (!empty($applied_coupons)) {
    $free_shipping_id = 'free_shipping:2';
    unset($packages[0]['rates'][ $free_shipping_id ]);
  }

  return $packages;
});

This is my first question on stack over flow but this site has helped me so much with so many issues. Forgive me if I am asking too much. Thanks in advance for any help/guidance.

Advertisement

Answer

Use instead woocommerce_package_rates filter hook. In the code below you will set the related coupon codes that will hide the free shipping method:

add_filter( 'woocommerce_package_rates', 'hide_free_shipping_method_based_on_coupons', 10, 2 );
function hide_free_shipping_method_based_on_coupons( $rates, $package )
{
    $coupon_codes       = array('summer'); // <== HERE set your coupon codes
    $applied_coupons    = WC()->cart->get_applied_coupons(); // Applied coupons
    
    if( empty($applied_coupons) )
        return $rates;

    // For specific applied coupon codes
    if( array_intersect($coupon_codes, $applied_coupons) ) {
        foreach ( $rates as $rate_key => $rate ) {
            // Targetting "Free shipping"
            if ( 'free_shipping' === $rate->method_id ) {
                unset($rates[$rate_key]); // hide free shipping method
            }
        }
    }
    return $rates;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Clearing shipping caches:

  • You will need to empty your cart, to clear cached shipping data
  • Or In shipping settings, you can disable / save any shipping method, then enable back / save.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement