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

WooCommerce如何在woocommerce_format_sale_price钩子中获取$cart_item对象

问题核心原因

woocommerce_format_sale_price过滤器默认仅传递3个价格相关参数,没有直接传入当前对应商品对象。商品详情页因为全局默认赋值了$product变量所以可以正常读取,但购物车/结账页是循环输出多个商品,全局$product不会动态对应到正在渲染的购物车商品,因此直接调用会抛出错误。


两种可行解决方案

方案1:使用自带商品参数的过滤器(推荐)

直接改用woocommerce_get_price_html过滤器修改价格样式,这个过滤器本身会传入$product参数,无论商品详情页、购物车、结账页调用都会自动匹配当前对应的商品对象,完全规避全局变量的兼容性问题:

add_filter( 'woocommerce_get_price_html', function( $price_html, $product ) {
    // 直接获取当前商品的自定义元字段
    $custom_meta = get_post_meta( $product->get_id(), '你的自定义字段Key', true );

    // 在这里写价格样式修改逻辑,调整$price_html即可
    return $price_html;
}, 10, 2 );

方案2:必须使用woocommerce_format_sale_price的实现方法

如果你的业务逻辑必须放在原过滤器中,可以通过临时全局变量的方式传递当前商品对象:

// 提前存储当前商品对象到临时变量,优先级设为9早于价格格式化过滤器执行
add_filter( 'woocommerce_get_price_html', function( $price_html, $product ) {
    global $tmp_current_render_product;
    $tmp_current_render_product = $product;
    return $price_html;
}, 9, 2 );

add_filter( 'woocommerce_format_sale_price', function( $price, $regular_price, $sale_price ) {
    global $tmp_current_render_product;

    // 判断商品对象有效后读取自定义字段
    if ( is_a( $tmp_current_render_product, 'WC_Product' ) ) {
        $custom_meta = get_post_meta( $tmp_current_render_product->get_id(), '你的自定义字段Key', true );
        // 你的业务逻辑写在这里
    }

    // 清空临时变量避免污染其他调用
    $tmp_current_render_product = null;
    return $price;
}, 10, 3 );

补充:购物车商品批量读取方法

如果需要单独遍历所有购物车商品获取元字段,可以直接调用WooCommerce全局购物车对象:

// 仅购物车/结账页生效
foreach ( WC()->cart->get_cart() as $cart_item ) {
    $product = $cart_item['data']; // 直接获取购物车商品对象
    $custom_meta = get_post_meta( $product->get_id(), '你的自定义字段Key', true );
    // 对应业务逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:27:04