WooCommerce 从属性中获取自定义字段

WooCommerce get custom field from attributte

是否可以从产品属性中获取自定义字段? 可以通过变体或产品 ID 连接吗? 我试过这个:

       function color_in_loop(){
        global $product;

        //Getting product attributes
        $attributes = $product->get_attributes();
        $values = wc_get_product_terms( $product->id, 'pa_color', array( 'fields' =>  'all' ) );
        
        foreach ( $values as $term ) {
            $icon = get_term_meta('product_attribute_color', 'pa_color_'.$term->term_id);
            echo $icon['url'];
        }
    }
add_action('woocommerce_after_shop_loop_item', 'color_in_loop');

你的get_term_meta错了,没必要用

$attributes = $product->get_attributes();

您可以简单地使用 get_the_terms 方法实现您正在寻找的内容,因为您知道您需要图标的特定属性。

function color_in_loop(){
    global $product;

    //Getting product attributes
    $product_id = $product->get_id();
    $colors = get_the_terms($product_id, 'pa_color');
    
    foreach ( $colors as $color ) {
        $icon = get_term_meta($color->term_id,'product_attribute_color',true);
        echo $icon['url'];
    }
}
add_action('woocommerce_after_shop_loop_item', 'color_in_loop');

它没有经过测试,但应该可以工作