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

如何从WooCommerce变体中获取全局属性的值?

解决WooCommerce变体无法获取父产品全局属性的问题

问题原因

你之前用get_meta('pa_material')获取全局属性是错误的——WooCommerce中带有pa_前缀的产品属性属于产品属性系统,并非存储为自定义元字段,因此不能通过get_meta()直接读取。

正确解决方案

修改你的代码,使用WooCommerce提供的产品属性专用方法来获取父产品的全局属性:

add_filter( 'woocommerce_get_price_html', 'bbloomer_alter_price_display', 9999, 2 );
function bbloomer_alter_price_display( $price, $product ) {
    if ( $product->is_type( 'variation' ) ) {   
        // 获取变体专属属性
        $variation_attributes = wc_get_product_variation_attributes($product->get_id());
        error_log(print_r($variation_attributes, true));

        // 获取父产品并读取全局属性
        $parent_id = $product->get_parent_id();
        $parent_product = wc_get_product($parent_id);
        
        if ( $parent_product ) {
            // 直接获取pa_material的属性值
            $material = $parent_product->get_attribute('pa_material');
            error_log('全局属性pa_material值:' . $material);
        }
    }
    return $price; // 必须返回价格,否则商品价格会显示为空
}

关键说明

  • get_attribute('pa_material'):WooCommerce专门用于读取产品属性的方法,会直接返回属性的显示值(单选属性返回字符串,多选属性返回逗号分隔的字符串)。
  • 增加父产品对象判断:避免因父产品不存在导致的报错。
  • 必须返回$price:过滤器函数需要返回修改后的(或原有的)价格字符串,否则商品价格区域会空白。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 13:07:41