如何在 woocommerce 中的自定义产品模板上获取自定义产品属性

How to get custom product attributes on custom product template in woocommerce

我使用 woocommerce 插件创建了一个可变产品。在可变产品中,我创建了一个自定义属性“许可期限”,其值为“3 个月|6 个月|1 年|生命周期” .

现在我想在自定义单品模板上显示这个属性。

我试过以下解决方案

1.

$licenseDurations = get_the_terms( $post->ID, 'attribute_license-duration' );

这显示了 var_dump($licenseDurations); `

object(WP_Error)[558]
  public 'errors' => 
    array (size=1)
      'invalid_taxonomy' => 
        array (size=1)
          0 => string 'Invalid taxonomy' (length=16)
  public 'error_data' => 
    array (size=0)
    empty`

2.

global $product;
$licenseDuration = $product->get_attribute( 'License Duration' ); // Here I also tried attribute slug `attribute_license-duration` instead of `License Duration` but no use

参考:

3.

global $product;
$licenseDurations = get_the_terms( $product->id, 'License Duration');

foreach ( $licenseDurations as $licenseDuration ) 
{
    echo $licenseDuration->name;
}

在上述两种情况下我什么都没得到,因为 $product;var_dump($product)

返回 null

4. 我也试过这个代码 http://isabelcastillo.com/woocommerce-product-attributes-functions

通过直接调用 isa_woo_get_one_pa() 我想显示值的地方。但没有运气。

这里有人帮忙...

您可以尝试以下方法

1.get_post_meta获取产品属性

$attr = get_post_meta( 123, '_product_attributes' ); // replace 123 with the actual product id 
print_r( $attr );

2.Or你可以创建一个产品对象然后使用get_attributes方法

$p = new WC_Product( 123 ); // // replace 123 with the actual product id 
print_r( $p->get_attributes() );

不确定woocommerce有没有变化,上面没有给出属性值。从这个 page 跟随 post 给出了正确答案

// 将 pa_attribute 替换为您的属性名称,但保留 pa_ 前缀
// 例如pa_weight

$fabric_values = get_the_terms( $product->id, 'pa_attribute');

foreach ( $fabric_values as $fabric_value ) {
  echo $fabric_value->name;
}

这里是所有产品属性列表。希望对你有帮助。

$product_attributes = get_post_meta( $post->ID, '_product_attributes' ); 
foreach ( $product_attributes as $group_attributes ) {
    foreach ( $group_attributes as $attributes ) {
      echo $attributes['name'].'=>'.$attributes['value'];
    }
}