我想根据购物车总数通过无线电输入选择本地取货运输方式。我用了这个代码
add_filter('woocommerce_package_rates', 'custom_modify_shipping_methods', 10, 2);
function custom_modify_shipping_methods($rates, $package) {
// Get the cart total
$cart_total = WC()->cart->subtotal;
// Set the threshold for choosing the local pickup shipping method
$threshold_amount = 2500;
// Check if the cart total is less than the threshold
if ($cart_total < $threshold_amount) {
// Loop through shipping rates
foreach ($rates as $rate_id => $rate) {
// Check if it's a local pickup method
if (strpos($rate_id, 'local_pickup') !== false) {
// Set the cost to zero (free)
$rates[$rate_id]->cost = 0;
}
}
}
return $rates;
}
此代码取消设置所有运输方式,它显示本地提货标签而不是无线电类型输入。输入类型被隐藏,由于未选择送货方式,我无法继续付款。如果购物车总数小于 2500,如何修改代码使本地提货方式默认选择其他方式?
当只有一种可用的运输方式时,相应的单选输入按钮将被隐藏,并且 WooCommerce 自动选择此可用的运输方式...
您使用的代码不适合您的需求。相反,请使用以下内容:
add_filter( 'woocommerce_package_rates', 'filter_shipping_package_rates', 10, 2 );
function filter_shipping_package_rates( $rates, $package ) {
$threshold_amount = 2600; // Here set the threshold amount
$subtotal_amount = 0; // Initializing variable
// Loop through cart items for the current shipping package
foreach( $package['contents'] as $item ){
$subtotal_amount += $item['line_subtotal'] + $item['line_subtotal_tax'];
}
// If cart items subtotal is up to the defined threshold amount
if ( $subtotal_amount >= $threshold_amount ) {
// Loop through shipping rates for the current shipping package
foreach( $rates as $rate_key => $rate ) {
// Targeting local pickup
if( 'local_pickup' === $rate->method_id ) {
$taxes = array(); // Initializing variable
// Loop through tax costs
foreach ($rate->taxes as $key => $tax) {
$taxes[$key] = 0; // Set tax cost to zero
}
$rates[$rate_key]->cost = 0; // Set cost to zero
$rates[$rate_key]->taxes = $taxes; // Set back taxes costs array
} else {
unset($rates[$rate_key]); // Remove other rates
}
}
}
return $rates;
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。
始终清空您的购物车,以刷新缓存的运输数据。