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

WooCommerce:特定商品分类+指定配送区域禁用下单按钮求助

解决WooCommerce购物车/结账页按商品分类+配送区域禁用下单按钮问题

原代码存在几个关键问题导致分类校验失效:

  • 未定义$product_id变量,has_term无法正常调用
  • 仅尝试检查单个商品,未遍历购物车所有商品判断是否存在目标分类商品
  • 未处理配送方式未选择时的空值情况
  • 提示信息的HTML标签写法错误

以下是修复后的完整代码:

add_filter('woocommerce_order_button_html', 'disable_checkout_button_for_category_and_zone' );
function disable_checkout_button_for_category_and_zone( $button ) {
    $targeted_zone_name = "Zone 4";
    $targeted_category = 'phones';
    $has_restricted_product = false;

    // 遍历购物车商品,检查是否存在目标分类商品
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $product = $cart_item['data'];
        if ( has_term( $targeted_category, 'product_cat', $product->get_id() ) ) {
            $has_restricted_product = true;
            break; // 找到一个就停止遍历
        }
    }

    // 未找到限制商品,直接返回原按钮
    if ( !$has_restricted_product ) {
        return $button;
    }

    // 获取选中的配送区域,处理未选择配送方式的情况
    $chosen_shipping_zone = null;
    $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
    if ( !empty( $chosen_shipping_methods ) ) {
        $chosen_shipping_method = reset( $chosen_shipping_methods );
        $chosen_shipping_method_parts = explode( ':', $chosen_shipping_method );
        if ( isset( $chosen_shipping_method_parts[1] ) ) {
            $shipping_instance_id = end( $chosen_shipping_method_parts );
            $chosen_shipping_zone = WC_Shipping_Zones::get_zone_by( 'instance_id', $shipping_instance_id );
        }
    }

    // 检查是否匹配目标配送区域
    if ( $chosen_shipping_zone && $targeted_zone_name === $chosen_shipping_zone->get_zone_name() ) {
        // 禁用按钮的样式
        $style = 'style="background:Silver !important; color:white !important; cursor: not-allowed !important; text-align:center;"';
        $button_text = apply_filters( 'woocommerce_order_button_text', __( 'Place order', 'woocommerce' ) );
        // 替换为禁用状态的按钮
        $button = '<a class="button" ' . $style . '>' . $button_text . '</a>';
        // 添加错误提示
        wc_add_notice( sprintf( __( '<strong>Error:</strong> Sorry we don\'t ship this product to your Zone. Please remove the item from the cart in order to checkout <a href="%s" class="button alt">My Cart</a>' ), get_permalink( get_option( 'woocommerce_cart_page_id' ) ) ), 'error' );
    }

    return $button;
}

关键修改说明:

  • 遍历购物车商品:通过WC()->cart->get_cart()遍历所有购物车商品,逐个检查是否属于目标分类,确保不会遗漏任何商品
  • 定义商品ID:通过$product->get_id()获取每个商品的ID,正确传入has_term函数
  • 空值处理:添加对配送方式未选择时的判断,避免因$chosen_shipping_zone为空导致的报错
  • 修复提示信息:修正了HTML标签的写法,同时将通知类型改为error(WooCommerce默认错误通知样式更醒目)
  • 函数命名优化:将原函数名改为更具语义的名称,便于后续维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:40:45