在“woocommerce_package_rates"中自定义税额;钩 [英] Customize Tax amount in "woocommerce_package_rates" hook
问题描述
我最近尝试使用钩子修改所有运费以应用折扣.
I recently tried to modify all my shipping rates with hook to apply discount.
这是我的代码:
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$
.
But one more step is the tax ! I got wrong tax.
For example I have my shipping rate who cost 3$
. With the discount, it's now 2,10$
.
我用 2$
购买一件商品,运费 2.10$
.我收到了 1 美元的税款(作为 3 美元的运费.看起来他没有接受更改),通常是 0.82$
.
I buy one item for 2$
and the shipping 2.10$
.
I got 1$ for the tax (as the 3$ shipping cost. look like he doesn't take the changes) and normally it's 0.82$
.
我需要什么才能获得正确的税收计算?
What do I need to get the correct tax calculation?
推荐答案
更新:关于运输方式的税费计算
Update: related to tax cost calculation for the shipping methods
您的代码有一些小错误,您错过了税收计算折扣.我重新审视了你的代码,你应该试试这个:
There is some little errors on your code and you have missed the tax calculation discount. I have revisited your code a bit, you should try this:
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 ($rate->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 文件或任何插件文件中.
此代码已经过测试且有效.
This code is tested and works.
您应该需要刷新运输缓存:
- 首先,此代码已保存在您的 function.php 文件中.
- 在配送设置中,输入配送区域并禁用配送方式并保存".然后重新启用该运输方式并保存".大功告成.
- First this code is already saved on your function.php file.
- In Shipping settings, enter in a Shipping Zone and disable a Shipping Method and "save". Then re-enable that Shipping Method and "save". You are done.
这篇关于在“woocommerce_package_rates"中自定义税额;钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!