Efb*_*fbi 3 php wordpress woocommerce tax
我最近尝试使用钩子修改我的所有运费以应用折扣。
这是我的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
但还有一步是税收!我把税搞错了。
例如,我有我的运费,费用为3$。有了折扣,现在就到了2,10$。
我购买一件商品2$并支付运费2.10$。我收到了 1 美元的税费(相当于 3 美元的运费。看起来他不接受零钱),通常是0.82$。
我需要什么才能获得正确的税收计算?
更新:添加税收成本计算,并删除了一些拼写错误。
您的代码有一些小错误,您错过了税收计算折扣。我重新审视了你的代码,你应该尝试一下:
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 ) {
// 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;
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或主题)的 function.php 文件中或任何插件文件中。
这段代码已经过测试并且可以工作。
您应该需要刷新运输缓存: