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

WooCommerce购物车葡萄酒品类统计及提示功能修复需求

解决方案:修复购物车葡萄酒数量统计与多数量提示问题

问题1:仅统计单款葡萄酒数量的修复

原代码找到第一个符合wein品类的商品后,执行break;直接终止循环,导致后续葡萄酒商品的数量未被累加。移除这个break;语句,循环就能遍历所有购物车商品,统计全部葡萄酒的总数量。

问题2:多数量触发提示的实现

用in_array()函数替代单个等于判断,把需要触发提示的数量放进数组,一次性检查当前总数量是否在目标数组内,高效处理多数量匹配需求。

修正后的完整代码

add_action( 'xoo_wsc_after_footer_btns', 'bbloomer_check_category_in_cart' );
function bbloomer_check_category_in_cart() {
    // 仅在购物车页面执行功能
    if ( ! is_cart() ) return;

    $cat_in_cart = false;
    $product_count = 0;

    // 遍历购物车所有商品
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // 检查商品是否属于wein品类
        if ( has_term( 'wein', 'product_cat', $cart_item['product_id'] ) ) {
            $cat_in_cart = true;
            // 累加当前商品的数量
            $product_count += $cart_item['quantity'];
        }
    }

    // 定义两组触发提示的数量数组
    $notice1_quantities = [10, 13, 16, 19];
    $notice2_quantities = [11, 14, 17, 20];

    if ( $cat_in_cart && in_array( $product_count, $notice1_quantities ) ) {
        wc_print_notice( 'Keine halben Sachen, nur noch 2 Flaschen und der Karton ist voll. Wir belohnen dich mit "due baci"', 'notice' );
    }

    if ( $cat_in_cart && in_array( $product_count, $notice2_quantities ) ) {
        wc_print_notice( 'Keine halben Sachen, nur noch 1 Flasche und der Karton ist voll. Wir belohnen dich mit "due baci"', 'notice' );
    }
}

关键修改说明

  1. 新增页面校验:添加if ( ! is_cart() ) return;确保功能仅在购物车页面生效,匹配需求要求。
  2. 移除终止循环的break:让循环完整遍历所有购物车商品,累加所有葡萄酒的数量。
  3. 数组批量匹配数量:用in_array()替代多个独立的==判断,代码更简洁易维护,后续新增触发数量只需修改数组即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:50:40