这是我用来根据购物车总额定义和设置运费的函数:
function adjust_shipping_rate( $rates, $package ) {
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
$cart_total = WC()->cart->get_subtotal();
// Define shipping rates based on cart total
$shipping_rates = [
['min' => 0, 'max' => 50, 'rate' => 20],
['min' => 50.1, 'max' => 100, 'rate' => 15],
['min' => 100.1, 'max' => 200, 'rate' => 10],
['min' => 200.1, 'max' => PHP_INT_MAX, 'rate' => 5]
];
// Find the appropriate shipping rate
foreach ($shipping_rates as $range) {
if ($cart_total >= $range['min'] && $cart_total <= $range['max']) {
foreach ($rates as $rate_key => $rate) {
if (strpos($rate_key, 'flat_rate') === 0) {
$rates[$rate_key]->cost = $range['rate'];
}
}
break;
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'adjust_shipping_rate', 10, 2 );
我确认,如果没有此功能,运费货币将被正确转换,但是使用此功能,成本保持不变,但格式正在转换。例如,5 美元运费不是转换为 4,61 欧元,而是转换为 5,00 欧元。
我们正在使用 WooPayments 及其多货币汇率。
如何获取当前的货币兑换率,以便我可以在我的函数中自己进行转换?我知道 get_woocommerce_currency() 获取货币代码,所以我希望有一些东西可以连接到 WooPayments 中设置的货币汇率,但我找不到任何类似的情况。
我的做法是错误的吗?如果不需要的话,我不想安装运费插件。
插件 WooPayments 插件似乎已经在使用
woocommerce_package_rates
钩子,因此降低钩子优先级可能会抢占先机,从而允许 WooPayments 插件转换在您的自定义运费上发挥作用。
此外,您的代码可以被简化/优化。最后,您当前的代码中缺少税率处理。
尝试以下操作:
add_filter( 'woocommerce_package_rates', 'custom_flat_rate_shipping_cost', 1, 2 );
function custom_flat_rate_shipping_cost( $rates, $package ) {
// Define shipping rates costs based on cart subtotal thresholds
$threshold_shipping_rate_cost = [
['threshold' => 200, 'rate' => 5],
['threshold' => 100, 'rate' => 10],
['threshold' => 50, 'rate' => 15],
['threshold' => 0, 'rate' => 20],
];
// Get Cart Subtotal excl. taxes for the current shipping package
$subtotal = $package['contents_cost'];
// Find the appropriate shipping rate
foreach ($rates as $rate_key => $rate) {
if ( 'flat_rate' !== $rate->method_id ) continue;
foreach ($threshold_shipping_rate_cost as $data) {
if ( $subtotal >= $data['threshold']) {
$base_cost = $rate->cost; // Original rate cost
$has_taxes = false; // Initializing
$taxes = array(); // Initializing
$rates[$rate_key]->cost = $data['rate']; // Set the new cost
// Loop through taxes array (change taxes rate cost if enabled)
foreach ($rate->taxes as $key => $tax){
if( $tax > 0 ){
$conv_rate = $tax / $base_cost; // Get the conversion tax rate
$taxes[$key] = $data['rate'] * $conv_rate; // Set the new tax cost in the array
$has_taxes = true; // Enabling tax changes
}
}
// Set the array of shipping tax cost (if any)
if( $has_taxes ) {
$rates[$rate_key]->taxes = $taxes;
}
break;
}
}
}
return $rates;
}
代码位于子主题的functions.php 文件中(或插件中)。它可以工作。
重要提示:您必须清空购物车才能刷新运输方式缓存。
请注意,
$package['contents_cost']
(或WC()->cart->get_subtotal()
)是购物车小计不含税。对于购物车小计包括税费,请使用 $package['cart_subtotal']
(或 WC()->cart->subtotal
)。