我提供 45 欧元免费送货服务。我隐藏了其他运输方式,除了本地提货,当可以使用下面的代码免费时。
add_filter( 'woocommerce_package_rates', 'hide_shipping_except_local_when_free_is_available', 100 );
function hide_shipping_except_local_when_free_is_available($rates) {
$free = $local = array();
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' === $rate->method_id ) {
$free[ $rate_id ] = $rate;
} elseif ( 'local_pickup' === $rate->method_id ) {
$local[ $rate_id ] = $rate;
}
}
return ! empty( $free ) ? array_merge( $free, $local ) : $rates;
}
我只是有一个小问题。超过 45 欧元的当地取货必须免费,且 45 欧元以下必须付费。在付款页面上,客户必须在 2 个免费选项(免费送货或免费本地取货)(如果可用)之间进行选择,或者在 2 个付费选项(标准运送 5 欧元或本地取货 5 欧元)(如果可用)之间进行选择。
若要提供 45 欧元的免费本地取货服务,请尝试使用以下代码替换(已注释):
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 100, 2 );
function filter_woocommerce_package_rates( $rates, $package ) {
$cart_subtotal = $package['cart_subtotal']; // Or use $package['contents_cost'] for excluding taxes
$threshold_amount = 45; // Min Cart subtotal
$free = $local = array(); // Initializing
// Loop through shipping rates for the current shipping package
foreach ( $rates as $rate_key => $rate ) {
if ( 'free_shipping' === $rate->method_id ) {
$free[$rate_key] = $rate;
} elseif ( 'local_pickup' === $rate->method_id ) {
// Set 'local_pickup' cost to zero if cart subtotal reach $threshold_amount
if ( $cart_subtotal >= $threshold_amount ) {
$taxes = array(); // Initializing
// Loop through tax costs
foreach ($rate->taxes as $key => $tax) {
$taxes[$key] = 0; // Set tax cost to zero
}
$rate->cost = 0; // Set cost to zero
$rate->taxes = $taxes; // Set back taxes costs array
}
$local[$rate_key] = $rate;
unset($rates[$rate_key]); // Remove 'local_pickup' from the main array
}
}
return ! empty( $free ) ? array_merge( $free, $local ) : array_merge( $local, $rates );
}
代码位于子主题的functions.php 文件中(或插件中)。应该可以。
重要提示:您必须清空购物车才能刷新运输方式缓存。
其他相关主题: