WooCommerce 本來有可以免運費的 coupon 可以用,但是他會直接新增一個免費運送的運送方式,在一邊的情況下很夠用,但是今天遇到的 CASE 則是因為串接了超商取貨,如果強制使用免費運送的運送方式的話就不能選超商取貨了,因此需求變成,套用免運費的時候,把全部的運送方式的費用變成 0,讓他繼續可以選擇超商取貨的運送方式。

方法如下:

  1. 一樣先建立免費運送的運送方式

  2. Coupon 的部分建立一個免運費的 Coupon

  3. 在 Theme 的function.php 裡面加上下面這段 code


    add_filter( 'woocommerce_package_rates', 'coupon_free_shipping_customization', 20, 2 );

    function coupon_free_shipping_customization( $rates, $package ) {
    $has_free_shipping = false;

    $applied_coupons = WC()->cart->get_applied_coupons();
    foreach( $applied_coupons as $coupon_code ){
    $coupon = new WC_Coupon($coupon_code);
    if($coupon->get_free_shipping()){
    $has_free_shipping = true;
    break;
    }
    }

    foreach( $rates as $rate_key => $rate ){
    if( $has_free_shipping ){
    // For "free shipping" method (enabled), remove it
    if( $rate->method_id == 'free_shipping'){
    unset($rates[$rate_key]);
    }
    // For other shipping methods
    else {
    // Append rate label titles (free)
    $rates[$rate_key]->label .= ' ' . __('(free)', 'woocommerce');

    // Set rate cost
    $rates[$rate_key]->cost = 0;

    // Set taxes rate cost (if enabled)
    $taxes = array();
    foreach ($rates[$rate_key]->taxes as $key => $tax){
    if( $rates[$rate_key]->taxes[$key] > 0 )
    $taxes[$key] = 0;
    }
    $rates[$rate_key]->taxes = $taxes;
    }
    }
    }
    return $rates;
    }

來源:Set all shipping methods cost to zero for a Free shipping coupon in Woocommerce