在 WooCommerce 中小计大于 0 时隐藏免费送货

Hide free shipping when subtotal is greater than 0 in WooCommerce

我正在为 WooCommerce 插件使用免费产品样品,并尝试仅为样品产品设置有条件的免费送货,样品产品成本为 0,因此我试图隐藏免费送货,除非订单小计金额为0.

简而言之:

我只想为样品产品提供免费送货服务,免费送货方式应该只对小计 = 0 的产品可见

进一步说明的截图:


我尝试的代码:

function ts_hide_shipping_for_order_total( $rates ) {
  $rate = array();
  $order_total = WC()->cart->get_subtotal();
  
  if( $order_total > 0 ) {
    foreach ( $rates as $rate_id => $rate ) {
      if ( 'free_shipping:20' === $rate->get_method_id() ) {
        $rate[ $rate_id ] = $rate;
      }
    }
  }
  return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'ts_hide_shipping_for_order_total', 100 );

add_filter( 'woocommerce_package_rates', 'hide_shipping_except_local_when_free_is_available', 100 );
function hide_shipping_except_local_when_free_is_available($rates) {
    $free = $local = array();

    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping:20' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
        }
    }
    return ! empty( $free ) ? array_merge( $free, $local ) : $rates;
}

但这两个代码都没有给我想要的结果。谁能指出我正确的方向?

要hide/unset“免运费”,只要小计大于0,就可以用下面的。

所以你得到:

function filter_woocommerce_package_rates( $rates, $package ) {
    // Get subtotal
    $subtotal = $package['cart_subtotal'];
    
    // Hide free shipping if subtotal > 0
    if ( $subtotal > 0 ) {
        // Loop trough
        foreach ( $rates as $rate_id => $rate ) {
            if ( $rate->method_id === 'free_shipping' ) {
                unset( $rates[$rate_id] );
            }
        }   
    }
    
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );

附加问题:小计<=0时隐藏其他方法

function filter_woocommerce_package_rates( $rates, $package ) { 
    // Get subtotal
    $subtotal = $package['cart_subtotal'];
    
    // Loop trough
    foreach ( $rates as $rate_id => $rate ) {
        if ( $rate->method_id === 'free_shipping' ) {
            // Hide free shipping if subtotal > 0
            if ( $subtotal > 0 ) {
                unset( $rates[$rate_id] );
            }
        } else {
            // Hide other methods when subtotal <= 0
            if ( $subtotal <= 0 ) {
                unset( $rates[$rate_id] );
            }               
        }
    }
    
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );