1 回答

TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
您提供的代碼中有很多錯(cuò)誤...以下內(nèi)容將允許您根據(jù)購物車小計(jì)百分比設(shè)置從5$
到最大值的運(yùn)費(fèi)。11$
首先,您需要在統(tǒng)一費(fèi)率設(shè)置中設(shè)置成本
5
(以及“UPS”作為標(biāo)簽)。
然后使用這段代碼:
add_filter( 'woocommerce_package_rates', 'woocommerce_package_rates', 10, 2 );
function woocommerce_package_rates( $rates, $package ) {
$max_cost = 11; // Here set the max cost for the shipping method
$percentage = 10; // Percentage to apply on cart subtotal
$subtotal = WC()->cart->get_subtotal(); // Cart subtotal without taxes
// Loop through shipping rates
foreach ( $rates as $rate_key => $rate ) {
// Targetting specific flate rate shipping method
if ( 'flat_rate:14' === $rate_key ) {
$has_taxes = false;
$base_cost = $rate->cost; // 5$ from this shipping method cost setting
$new_cost = $subtotal * $percentage / 100; // Calculation
if( $new_cost > $base_cost ) {
// 1. Rate cost
if ( $new_cost < $max_cost ) {
$rates[$rate_key]->cost = $new_cost;
$rate_operand = $new_cost / $base_cost; // (for taxes if enabled)
} else {
$rates[$rate_key]->cost = $max_cost;
$rate_operand = $max_cost / $base_cost; // (for taxes if enabled)
}
// 2. Taxes rate cost (if enabled)
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $tax > 0 ){
// New tax calculated cost
$taxes[$key] = $tax * $rate_operand;
$has_taxes = true;
}
}
// Set new taxes cost
if( $has_taxes ) {
$rates[$rate_key]->taxes = $taxes;
}
}
}
}
return $rates;
}
代碼位于活動(dòng)子主題(或活動(dòng)主題)的functions.php 文件中。經(jīng)過測試并有效。
刷新運(yùn)輸緩存:
此代碼已保存在您的functions.php 文件中。
在運(yùn)輸區(qū)域設(shè)置中,禁用/保存任何運(yùn)輸方式,然后啟用返回/保存。
你已經(jīng)完成了,你可以測試它。
- 1 回答
- 0 關(guān)注
- 125 瀏覽
添加回答
舉報(bào)