WooCommerce - 获取自定义产品属性

WooCommerce - Get custom product attribute

我正在尝试在 woocommerce 中获取特定的自定义属性。 我已经阅读了该站点上的大量线程,它们提供了大约 3-5 种方法来实现这一点。 尝试所有方法后,唯一对我有用的方法是遍历所有属性——所有其他方法都不起作用。 我有一个名为 'pdfs'

的自定义属性

以下尝试无效: (link)

 $global product;
 $myPdf = array_shift( wc_get_product_terms( $product->id, 'pdfs', array( 'fields' => 'names' ) ) );

 $myPdf = $product->get_attribute( 'pdfs' );

 $myPdf = get_post_meta($product->id, 'pdfs', true);

这是唯一有效的方法: (link)

 $attributes = $product->get_attributes();
 foreach ( $attributes as $attribute ) {
    if (attribute_label( $attribute[ 'name' ] ) == "pdfs" ) {
        echo array_shift( wc_get_product_terms( $product->id,  $attribute[ 'name' ] ) );
    }
}

我更希望能够使用第一个选项 任何帮助将不胜感激。
谢谢

Update: Added compatibility for Woocommerce 3+

由于数据库中的属性总是以 pa_ 开头,为了使用 wc_get_product_terms() 函数获取它们,您将需要使用 pa_pdfs 而不是 pdfs,这样:

global $product;

$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id; // Added WC 3+ support

$myPdf = array_shift( wc_get_product_terms( $product_id, 'pa_pdfs', array( 'fields' => 'names' ) ) );

参考:How to get a products custom attributes from WooCommerce