我最近试图用挂钩修改我的所有运费以应用折扣。
这是我的代码:
add_filter( 'woocommerce_package_rates', 'woocommerce_package_rates' );
function woocommerce_package_rates( $rates ) {
$user_id = get_current_user_id();
if ( ! wc_memberships_is_user_active_member( $user_id, 'silver' ) ) { return $rates; }
$discount_amount = 30; // 30%
foreach($rates as $key => $rate ) {
$rates[$key]->cost = $rates[$key]->cost - ( $rates[$key]->cost * ( $discount_amount/100 ) );
}
return $rates;
}
但还有一步就是税收!我的税收错了。
例如,我的运费为3$
。有了折扣,它现在是2,10$
。
我为2$
和发货2.10$
购买了一件商品。
我得到1美元的税(因为3美元的运费。看起来他没有做出改变),通常它是0.82$
。
我需要什么才能获得正确的税收计算?
答案 0 :(得分:4)
更新与运费方法的税费计算相关
您的代码存在一些小错误,而您错过了计税折扣。我稍微重新审视了你的代码,你应该试试这个:
add_filter( 'woocommerce_package_rates', 'conditional_shipping_discount', 10, 2 );
function conditional_shipping_discount( $rates, $packages ) {
$user_id = get_current_user_id();
if ( ! wc_memberships_is_user_active_member( $user_id, 'silver' ) ) return $rates;
$percent = 30; // 30%
$discount = 1 - ($percent / 100);
foreach($rates as $rate_key => $rate_values ) {
// Get original cost
$original_cost = $rates[$rate_id]->cost;
// Calculate the discounted rate cost
$new_cost = $original_cost * $discount;
// Set the discounted rate cost
$rates[$rate_key]->cost = number_format(new_cost, 2);
// calculate the conversion rate (for taxes)
$conversion_rate = $new_cost / $original_cost;
// Taxes rate cost (if enabled)
$taxes = array();
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $tax > 0 ){ // set the new tax cost
// set the new line tax cost in the taxes array
$taxes[$key] = number_format( $tax * $conversion_rate, 2 );
}
}
// Set the new taxes costs
$rates[$rate_key]->taxes = $taxes
}
return $rates;
}
代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。
此代码经过测试并有效。
您需要刷新送货缓存:
1)首先,此代码已保存在function.php文件中。
2)在运输设置中,输入运输区域并禁用运输方式和“保存”。然后重新启用送货方式和“保存”。 你已经完成了。
答案 1 :(得分:0)
@LoicTheAztec代码下面,没有错误:
add_filter( 'woocommerce_package_rates', 'conditional_shipping_discount', 10, 2 );
function conditional_shipping_discount( $rates, $packages ) {
$user_id = get_current_user_id();
if ( ! wc_memberships_is_user_active_member( $user_id, 'silver' ) ) return $rates;
$percent = 30; // 30%
$discount = 1 - ($percent / 100);
foreach($rates as $rate_key => $rate_values ) {
// Get original cost
$original_cost = $rates[$rate_key]->cost;
// Calculate the discounted rate cost
$new_cost = $original_cost * $discount;
// Set the discounted rate cost
$rates[$rate_key]->cost = number_format($new_cost, 2);
// calculate the conversion rate (for taxes)
$conversion_rate = $new_cost / $original_cost;
// Taxes rate cost (if enabled)
$taxes = array();
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $tax > 0 ){ // set the new tax cost
// set the new line tax cost in the taxes array
$taxes[$key] = number_format( $tax * $conversion_rate, 2 );
}
}
// Set the new taxes costs
$rates[$rate_key]->taxes = $taxes;
}
return $rates;
}