我正在尝试为当前在购物车中的产品的一个运输类别应用折扣。这适用于结帐视图。
在 Woocommerce 后端,该选项设置为单独对每个运输类别收费。另外,我只使用一种名为“统一费率”的运输方式。
基于Override all shipping costs for a specific shipping class in Woocommerce,以下代码应应用折扣:
add_filter('woocommerce_package_rates', 'shipping_class_null_shipping_costs', 10, 2);
function shipping_class_null_shipping_costs( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
$shipping_class_slug = 'large'; // Your shipping class slug
$found = false;
// Loop through cart items and checking for the specific defined shipping class
foreach( $package['contents'] as $cart_item ) {
if( $cart_item['data']->get_shipping_class() == $shipping_class_slug )
$found = true;
}
$percentage = 50; // 50%
$subtotal = WC()->cart->get_cart_shipping_total();
// Set shipping costs to 50% discount if shipping class is found
if( $found ){
foreach ( $rates as $rate_key => $rate ){
$has_taxes = false;
// Targetting "flat rate"
if( 'flat_rate' === $rate->method_id ){
$rates[$rate_key]->cost = $subtotal;
}
}
}
return $rates;
}
但无论我尝试什么,计算出的运费结果都是 0 美元。
我在这里做错了什么,对航运类应用折扣的正确方法是什么?
谢谢你。