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

如何针对WooCommerce购物车中的第2、3、4项设置不同显示?

WooCommerce购物车商品位置对应GravityView短代码问题修复

问题场景

需求是根据购物车中商品的位置(第1、2、3项等),为每个商品显示对应的GravityView短代码。当前实现仅在购物车只有1件商品时正常;当有2件及以上商品时,所有商品会同时显示多个短代码,不符合预期。

错误原因

  1. 动态添加过滤器的问题:你在遍历购物车商品时,循环添加了多个woocommerce_cart_item_name过滤器。这些过滤器会全局作用于所有购物车商品,而非单个商品。比如遍历到第2件商品时新增的过滤器,会让所有商品都被两个过滤器处理,导致短代码叠加。
  2. 函数嵌套定义问题:在name_on_cart_item函数内部嵌套定义了两个处理函数,这不符合PHP规范,可能导致重复定义错误。

修正后的代码

// 存储购物车商品的位置序号
add_action( 'woocommerce_before_calculate_totals', 'store_cart_item_positions', 10, 1 );
function store_cart_item_positions( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return; 

    $count = 0;
    // 遍历购物车,给每个商品标记位置
    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {  
        $count++;
        $cart_item['position'] = $count;
    }
}

// 根据商品位置添加对应GravityView短代码
add_filter( 'woocommerce_cart_item_name', 'custom_text_cart_item_name_by_position', 9, 3 );
add_filter( 'woocommerce_cart_item_name', 'do_shortcode', 11 );

function custom_text_cart_item_name_by_position( $item_name, $cart_item, $cart_item_key ) {
    // 获取商品在购物车中的位置
    $position = isset( $cart_item['position'] ) ? $cart_item['position'] : 0;

    // 按位置匹配对应的短代码
    switch( $position ) {
        case 1:
            $shortcode = '[gravityview id="1471"]';
            break;
        case 2:
            $shortcode = '[gravityview id="1569"]';
            break;
        // 可扩展更多位置的短代码
        default:
            $shortcode = '';
            break;
    }

    if ( $shortcode ) {
        $item_name = '<div class="item-shipping-class">' . __( $shortcode, "woocommerce" ) . '</div>' . $item_name;
    }

    return $item_name;
}

代码逻辑说明

  1. 存储商品位置:通过woocommerce_before_calculate_totals钩子遍历购物车,为每个商品添加position属性,记录它在购物车中的序号。
  2. 统一处理过滤器:只添加一次woocommerce_cart_item_name过滤器,在处理函数中根据商品的position值,选择对应的短代码添加到商品名称前。
  3. 避免叠加问题:每个商品只会根据自身位置匹配对应的短代码,不会被多个过滤器同时处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:45:36