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

WooCommerce如何按自定义元数据分组合并同商品的购物车项?

解决方案

你当前代码无法合并相同test标题购物车项的核心原因是:每次添加购物车时都生成了完全随机的unique_key,导致不管test_title是否匹配,WooCommerce都会判定为不同的独立购物车项,不会触发数量累加逻辑。

完整修改代码

add_filter( 'woocommerce_add_cart_item_data', 'add_cart_simple_product_custom_price', 20, 2 );
function add_cart_simple_product_custom_price( $cart_item_data, $product_id ) {
    // 替换为你站点testare-psihologica商品的实际ID
    $target_product_id = 123;
    // 仅对目标商品、携带test参数的请求做处理
    if( $product_id != $target_product_id || !isset( $_GET['test'] ) ) {
        return $cart_item_data;
    }

    // 安全过滤+参数有效性校验
    $test_slug = sanitize_text_field( $_GET['test'] );
    $test = get_page_by_path( $test_slug, OBJECT, 'tests' );
    if( !$test ) {
        return $cart_item_data;
    }
    
    $test_title = get_post_field( 'post_title', $test->ID );
    $cart_item_data['test_title'] = $test_title;

    // 用商品ID+test标题生成唯一key,相同配置的商品key完全一致
    $unique_cart_item_key = md5( $product_id . $test_title );
    $cart_item_data['unique_key'] = $unique_cart_item_key;

    return $cart_item_data;
}

// 会话恢复钩子,确保刷新页面后自定义元数据不丢失
add_filter( 'woocommerce_get_cart_item_from_session', 'restore_custom_cart_item_meta', 20, 2 );
function restore_custom_cart_item_meta( $cart_item, $values ) {
    if( isset( $values['test_title'] ) ) {
        $cart_item['test_title'] = $values['test_title'];
    }
    return $cart_item;
}

// 【可选】将test标题写入订单项,后台订单、客户邮件都会展示
add_action( 'woocommerce_checkout_create_order_line_item', 'add_test_title_to_order_item', 20, 4 );
function add_test_title_to_order_item( $item, $cart_item_key, $values, $order ) {
    if( isset( $values['test_title'] ) ) {
        $item->add_meta_data( '关联测试标题', $values['test_title'], true );
    }
}

核心修改说明

  • 替换了随机unique_key生成规则:改为基于商品ID+test标题生成哈希值,相同商品相同test标题的哈希值完全一致,WooCommerce会自动识别为同个购物车项,仅累加数量
  • 增加了参数安全校验:对用户传入的test参数做了安全过滤,同时增加了test存在性判断,避免无效参数导致的代码报错
  • 新增了会话数据恢复钩子:确保用户刷新购物车页面后,自定义的test_title元数据不会丢失
  • 可选补充了订单元数据写入逻辑:如果已经有额外逻辑处理test标题的展示和订单写入,可以删除对应部分

注意事项

  • 务必将代码中$target_product_id的取值替换为你站点testare-psihologica商品的实际数字ID
  • 如果你需要保留不同数量的自定义定价逻辑,可以额外结合woocommerce_before_calculate_totals钩子实现,和当前合并逻辑不冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:36:03