如何在WooCommerce中根据购物车总额默认选择自提配送方式?
解决WooCommerce购物车总额低于阈值时默认选中自提并隐藏其他配送方式的问题
需求:根据购物车总额,当总额低于2500时,默认选中自提(local pickup)配送方式,并取消其他配送方式。
原代码问题:使用以下代码后,所有配送方式被取消,仅显示自提标签但单选框隐藏,无法选择并继续支付: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; }
修改后的代码
add_filter('woocommerce_package_rates', 'custom_modify_shipping_methods', 10, 2); function custom_modify_shipping_methods($rates, $package) { // 获取购物车小计 $cart_total = WC()->cart->subtotal; // 设置触发阈值 $threshold_amount = 2500; if ($cart_total < $threshold_amount) { $filtered_rates = array(); // 遍历所有配送方式,仅保留自提选项 foreach ($rates as $rate_id => $rate) { if (strpos($rate_id, 'local_pickup') !== false) { // 可选:设置自提费用为0 $rate->cost = 0; $filtered_rates[$rate_id] = $rate; } } // 确保存在自提方式时替换原数组 if (!empty($filtered_rates)) { $rates = $filtered_rates; } } return $rates; }
代码说明
- 核心改动:不再仅修改自提方式的费用,而是直接过滤掉所有非自提的配送方式,只保留自提选项的完整数据,保证单选框正常显示,用户可选中并继续支付流程。
- 保留自提方式的全部属性,避免原代码中可能导致的配送方式结构异常问题。
- 自提费用设置为0是可选操作,可根据实际业务需求调整。
生效注意事项
修改代码后,需进入WooCommerce后台的「设置-配送」页面,点击一次「保存更改」清空配送缓存,确保新规则立即生效。
内容的提问来源于stack exchange,提问作者Robert Zalinyan
相关产品推荐
相关产品推荐

