WooCommerce 禁用特定配送方式下单按钮 兼容order-pay
问题根因
- 原代码的页面判定逻辑存在兼容漏洞:WooCommerce 内置的
is_checkout()函数会把所有结账体系下的页面(普通结账页、order-pay 支付页、order-received 订单完成页)都返回true,搭配is_wc_endpoint_url()的判断如果早于WordPress全局查询变量初始化完成,就会失效,导致order-pay端点识别错误,规则被错误套用到支付页上。 - 原代码对配送方式session值没做空值防护,当session返回空数组时,
in_array判断容易出现不可预期的执行结果。
修正后可直接使用的代码
add_filter('woocommerce_order_button_html', 'disable_place_order_button_html' ); function disable_place_order_button_html( $button ) { // 精准限定生效范围:仅原生购物车结账页触发规则,排除所有支付类端点 if( is_page( wc_get_page_id('checkout') ) // 识别嵌入结账短码的原生页面 && ! is_wc_endpoint_url( 'order-pay' ) && ! is_wc_endpoint_url( 'order-received' ) ) { // 替换成你要拦截的目标配送方式ID $targeted_shipping_method = "table_rate:3"; // 安全获取已选配送方式,增加空值判断避免程序报错 $chosen_shipping_methods = WC()->session ? WC()->session->get('chosen_shipping_methods') : array(); // 匹配到目标配送方式时,替换按钮为不可点击状态 if( !empty($chosen_shipping_methods) && in_array( $targeted_shipping_method, $chosen_shipping_methods ) ) { $style = 'style="background:Silver !important; color:white !important; cursor: not-allowed !important; text-align:center;"'; $text = apply_filters( 'woocommerce_order_button_text', __( 'Place order', 'woocommerce' ) ); $button = '<a class="button" '.$style.'>' . $text . '</a>'; } } return $button; }
使用提示
- 目标配送方式ID可以在WooCommerce配送设置页面找到,格式一般为「配送类名:实例编号」,和代码里的示例格式保持一致即可。
- 这段代码严格限定了仅在原生结账页生效,order-pay端点、订单完成页的按钮完全不会被修改,不存在原问题中的越权拦截问题。
- 代码增加了session存在性判断,避免在REST API请求、session未初始化等极端场景下触发PHP报错。
内容的提问来源于stack exchange,提问作者fabiocs81
相关产品推荐
相关产品推荐

