首页 > 解决方案 > WooCommerce 从属性中获取自定义字段

问题描述

是否可以从产品属性中获取自定义字段?并且可以通过变体或产品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');

标签: phpwordpresswoocommercehook-woocommerce

解决方案


你的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');

它未经测试,但应该可以工作


推荐阅读