根据含税价格修改产品价格



我正在建一家Wooccommerce商店,我需要得到所有含税价格,以零结尾(例如,如果含税原价是1234,那么我将其四舍五入到1240(。

产品是批量进口到我的网站上的(+2800种产品(,但它们的价格是免税的。我在wooccommerce设置中配置了税,并显示商店中包含税的价格。

为了修复";以0"结尾;问题是,我创建了一个方法来更改税值,以便最终价格以0:结束

// Calculate tax
function filter_woocommerce_calc_tax( $taxes, $price, $rates, $price_includes_tax, $suppress_rounding ) { 
$key = array_search('IVA', array_column_keys($rates, 'label')); // find tax with label "IVA"
$tax = $taxes[$key]; // get the current tax
$subtotal = $price + $tax; // get the total
$final = ceil($subtotal / 10) * 10; // modify the total so it ends in 0
$new_tax = $final - $price; // calculate new tax price
$taxes[$key] = $new_tax; // update tax in array
return $taxes; // return new calculated taxes
};
add_filter( 'woocommerce_calc_tax', 'filter_woocommerce_calc_tax', 10, 5 ); 

这真的很好,但我想如果我改变税率,我实际上就是在改变税率(%(,出于法律原因我不能这样做。

这就是为什么我想在不征税的情况下改变产品的价格。

我可以使用相同的方法:

$final = ceil($subtotal / 10) * 10; // modify the total so it ends in 0
$new_price = $final - $tax; // new price without tax

但我不知道该用什么钩子来实现这一点。

可以用挂钩和过滤器改变价格吗?

我终于找到了一个解决方案,首先我创建了一种无税计算价格的方法:

function get_net_sales_price($price, $tax_rate = 0) {
$subtotal = $price + (1+$tax_rate);
$final = ceil($subtotal / 10) * 10;
$new_price = $final / (1+$tax_rate);
return $new_price;
}

然后我得到了基于产品和客户位置的税收(多亏了这个答案(:

function get_tax_rates($product) {
// Get an instance of the WC_Tax object
$tax_obj = new WC_Tax();
// Get the tax data from customer location and product tax class
return $tax_obj->find_rates(array(
'country'   => WC()->customer->get_shipping_country() ? WC()->customer->get_shipping_country() : WC()->customer->get_billing_country(),
'state'     => WC()->customer->get_shipping_state() ? WC()->customer->get_shipping_state() : WC()->customer->get_billing_state(),
'city'      => WC()->customer->get_shipping_city() ? WC()->customer->get_shipping_city() : WC()->customer->get_billing_city(),
'postcode'  => WC()->customer->get_shipping_city() ? WC()->customer->get_shipping_city() : WC()->customer->get_billing_city(),
'tax_class' => $product->get_tax_class()
));
}

最后,我用钩子返回产品的正确价格(wooccommerce然后在需要时添加税(:

function filter_woocommerce_price($price, $product) {
$rates = get_tax_rates($product);
// Finally we get the tax rate and calculare net sales price:
if( ! empty($rates) ) {
$key = array_search('IVA', array_column_keys($rates, 'label'));
return get_net_sales_price($price, $rates[$key]['rate'] / 100);
} else {
return get_net_sales_price($price);
}
}
add_filter('woocommerce_product_get_price', 'filter_woocommerce_price', 99, 2 );
add_filter('woocommerce_product_get_regular_price', 'filter_woocommerce_price', 99, 2 );
add_filter('woocommerce_product_variation_get_regular_price', 'filter_woocommerce_price', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'filter_woocommerce_price', 99, 2 );

现在我得到了正确的税额,而且所有产品的价格都以0结尾。

最新更新