You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce购物车总额<$150时自提配送单选按钮异常隐藏问题

解决WooCommerce购物车总额低于150美元时自提选项单选按钮隐藏的问题

问题场景

需求:当购物车总额低于150美元时,隐藏除Local Pickup(自提)外的所有配送方式。
编写代码如下:

function hide_shipping_for_order_total( $rates ) {
    $order_total = WC()->cart->get_subtotal();

    if( $order_total < 150 ) {
        foreach ( $rates as $rate_id => $rate ) {
            if ( 'local_pickup' !== $rate->get_method_id() ) {
                unset( $rates[ $rate_id ] );
            }
        }
    }

    return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_shipping_for_order_total', 100 );

问题:代码可隐藏其他配送方式,但购物车总额低于150美元时,Local Pickup的单选按钮被设为隐藏状态;总额高于150美元时,Local Pickup可正常显示。

问题原因

这是WooCommerce的默认行为:当页面上只剩下唯一的配送选项时,系统会自动隐藏该选项的单选按钮,同时自动选中它,但视觉上会让用户误以为自提选项消失了,影响体验。

修复方案

在保留原逻辑的基础上,强制前端显示自提选项的单选按钮,调整后的代码如下:

function hide_shipping_for_order_total( $rates ) {
    $order_total = WC()->cart->get_subtotal();

    if( $order_total < 150 ) {
        // 筛选出仅自提配送方式
        $filtered_rates = array_filter( $rates, function( $rate ) {
            return 'local_pickup' === $rate->get_method_id();
        });
        
        // 确认存在自提选项后替换原数组
        if( !empty( $filtered_rates ) ) {
            $rates = $filtered_rates;
            
            // 注入CSS强制显示单选按钮
            add_action( 'wp_footer', function() {
                ?>
                <style>
                    .woocommerce-shipping-methods .shipping_method input[type="radio"] {
                        display: inline-block !important;
                        opacity: 1 !important;
                        position: static !important;
                    }
                    .woocommerce-shipping-methods .shipping_method label {
                        padding-left: 25px !important;
                    }
                </style>
                <?php
            });
        }
    }

    return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_shipping_for_order_total', 100 );

代码说明

  • 用array_filter替代循环unset,代码更简洁高效
  • 通过wp_footer钩子添加自定义CSS,强制覆盖WooCommerce隐藏单选按钮的默认样式
  • 仅在总额低于150且存在自提选项时才注入CSS,避免不必要的样式干扰

内容的提问来源于stack exchange,提问作者Junky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 21:55:20