doufang2023 2018-08-08 23:02
浏览 60
已采纳

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

In Woocommerce, I have added a hooked function which displays the product attribute for variation assigned to a variable product on the Woocommerce archive pages:

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>'; 
            } 
        }
    }
}

It is working fine, but some of the data is messy… I only want to display 'Size' product attribute for variation values, not all the products that have a "size" attribute.

  • 写回答

1条回答 默认 最新

  • duanhao9176 2018-08-08 23:59
    关注

    If you want to target the product attribute for variation "size" to get the corresponding values from the product variations set for the variable product, try the following:

    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>';
            }
        }
    }
    

    Code goes in function.php file of your active child theme (or theme). tested and works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示