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

如何在WooCommerce中获取产品变体并添加至Stripe支付元数据?

如何在WooCommerce Stripe元数据中添加产品已选变体选项

我来帮你调整代码,把产品的已选变体信息添加到Stripe的支付元数据里。核心思路是利用WooCommerce变体产品对象的内置方法获取用户选择的变体属性,再整合到你现有的元数据结构中。

修改后的完整代码

function filter_wc_stripe_payment_metadata( $metadata, $order, $source ) {
    $count = 1;
    foreach( $order->get_items() as $item_id => $line_item ){
        $item_data = $line_item->get_data();
        $product = $line_item->get_product();
        $location = $product->get_attribute('location');
        $product_name = $product->get_name();
        $item_quantity = $line_item->get_quantity();
        $item_total = $line_item->get_total();
        
        // 初始化商品描述文本
        $item_description = "{$product_name} | 数量: {$item_quantity} | 总价: {$item_total}";
        
        // 检查是否为变体产品,获取已选变体属性
        if ( $product->is_type( 'variation' ) ) {
            $variation_attributes = $product->get_variation_attributes();
            $variation_text = [];
            foreach ( $variation_attributes as $attr_slug => $attr_value ) {
                // 将属性slug转换为友好名称(比如pa_color → "Color")
                $attr_label = wc_attribute_label( str_replace('pa_', '', $attr_slug) );
                $variation_text[] = "{$attr_label}: {$attr_value}";
            }
            // 把变体信息拼接到商品描述中
            if ( !empty($variation_text) ) {
                $item_description .= " | 变体: " . implode(', ', $variation_text);
            }
        }
        
        // 添加上已有的location属性(如果存在)
        if ( !empty($location) ) {
            $item_description .= " | 位置: {$location}";
        }
        
        // 更新元数据
        $metadata['Item '.$count] = $item_description;
        $count += 1;
    }
    return $metadata;
}
add_filter( 'wc_stripe_payment_metadata', 'filter_wc_stripe_payment_metadata', 10, 3 );

关键部分说明

  • 变体产品判断:用$product->is_type( 'variation' )检查当前商品是否为变体产品,避免对简单产品执行无效操作。
  • 获取变体属性:$product->get_variation_attributes()会返回一个数组,包含用户选择的所有变体属性(键是属性slug,比如pa_size;值是选中的选项,比如Large)。
  • 属性名称友好化:通过wc_attribute_label()把属性slug转换成用户易懂的名称,让元数据更易读。
  • 信息整合:把变体属性、商品名称、数量、总价等信息拼接成清晰的字符串,添加到对应的Item X元数据字段中。

修改后,你的Stripe支付记录里就能看到包含变体选项的完整商品信息,方便后续对账和订单细节查看。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:17:33