首页 文章

显示Woocommerce存档页面中变体的大小产品属性值

提问于
浏览
1

在Woocommerce中,我添加了一个钩子函数,该函数显示分配给Woocommerce存档页面上的变量产品的变体的产品属性:

add_action( 'woocommerce_after_shop_loop_item', 'stock_variations_loop' );
function stock_variations_loop(){
    global $product;

    if ( $product->get_type() == 'variable' ) {
        foreach ($product->get_available_variations() as $key) {
            $attr_string = '';

            foreach ( $key['attributes'] as $attr_name => $attr_value) {
                $attr_string[] = $attr_value;
            }
            if ( $key['max_qty'] > 0 ) { 
                echo '<div class="sizeVariantCat">' . implode(', ', $attr_string).'</div>'; 
            } 
        }
    }
}

它工作正常,但有些数据很混乱...我只想显示变量值的'Size'产品属性,而不是所有具有“size”属性的产品 .

1 回答

  • 1

    如果要将变量“size”的product属性作为目标,以从变量product的产品变体集中获取相应的值,请尝试以下操作:

    add_action( 'woocommerce_after_shop_loop_item', 'display_attribute_size_for_variations' );
    function display_attribute_size_for_variations(){
        global $product;
    
        // HERE the taxonomy for the targeted product attribute
        $taxonomy = 'pa_size';
    
        if ( $product->get_type() == 'variable' ) {
            $output = array();
            foreach ($product->get_available_variations() as $values) {
                foreach ( $values['attributes'] as $attr_variation => $term_slug ) {
                    // Targetting "Size" attribute only
                    if( $attr_variation === 'attribute_' . $taxonomy ){
                        // Add the size attribute term name value to the array (avoiding repetitions)
                        $output[$term_slug] = get_term_by( 'slug', $term_slug, $taxonomy )->name;
                    }
                }
            }
            if ( sizeof($output) > 0 ) {
                echo '<div class="'.$taxonomy.'-variations-terms">' . implode( ', ', $output ).'</div>';
            }
        }
    }
    

    代码位于活动子主题(或主题)的function.php文件中 . 测试和工作 .

相关问题