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

如何在PHP WooCommerce中实现购物车含指定字符时输出文本?

修复WooCommerce购物车商品名称匹配问题的解决方案

原代码的核心问题

  • 循环中每次覆盖$product_name变量,最终仅保留最后一个商品的名称,导致只有最后一个商品匹配时才会触发输出。
  • 使用in_array()做精确匹配,但需求是商品名称包含数组中的任一字符串,逻辑完全不符。

修正后的代码

add_action( 'woocommerce_review_order_before_submit', 'review_order_before_submit_state_message' );
function review_order_before_submit_state_message() {
    // 定义需要匹配的关键词数组
    $target_keywords = array('Fiat', 'Mercedez', '05150993');
    $match_found = false;

    // 遍历购物车所有商品
    foreach(WC()->cart->get_cart() as $cart_item){
        $product_name = $cart_item['data']->get_name();
        
        // 检查当前商品名称是否包含任一关键词
        foreach($target_keywords as $keyword){
            // 转小写实现不区分大小写匹配,需严格区分可移除strtolower()
            if(strpos(strtolower($product_name), strtolower($keyword)) !== false){
                $match_found = true;
                break 2; // 跳出两层循环,无需继续检查
            }
        }
    }

    // 找到匹配则输出指定文本
    if($match_found){
        echo '<span>Some Text</span>';
    }
}

代码改进说明

  1. 新增$match_found标记,统一管理匹配状态,避免单商品覆盖问题。
  2. 嵌套循环实现「商品名称包含任一关键词」的逻辑:外层遍历购物车商品,内层遍历关键词数组,用strpos()检查包含关系。
  3. 找到匹配后直接跳出两层循环,减少不必要的遍历,提升执行效率。
  4. 可选调整:若需要严格区分大小写匹配,移除代码中的strtolower()即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:10:39