代码之家  ›  专栏  ›  技术社区  ›  Shehab Eltawel

获取变体属性

  •  5
  • Shehab Eltawel  · 技术社区  · 7 年前

    我试图在定制产品页面上获得可变产品的变体。我有两个属性,一个用于选择大小,另一个用于样例颜色。问题是我无法显示需要显示的属性,当我使用以下代码时,它返回大小或颜色的文本名称,而不是大小或颜色样例的选择下拉列表。有什么帮助吗?!

    echo implode(', ', wc_get_product_terms( $product_id, 'pa_colors' )); 
    
    1 回复  |  直到 7 年前
        1
  •  17
  •   Jose Carlos Ramos Carmenates    7 年前

    这是一个简单的代码来解决你的问题,我让你完整的代码,你可以只使用你需要的。

    第一个是检查 get_product $idProduct ).

    if( function_exists('get_product') ) {
            $product = get_product( $idProduct );
            if ( $product->is_type( 'variable' ) ) {
    
                $product = new WC_Product_Variable( $idProduct );
    
                $available_variations = $product->get_available_variations(); //get all child variations
                $variation_variations = $product- >get_variation_attributes(); // get all attributes by variations
    
                // taxonomy           => terms
                // pa_attribute-color => array('blue', 'red', green)
                // Use ex: get_taxonomy('pa_attribute-color')->labels; to get the Name and not the slug to attributes, it can be the taxonomy
                // Use ex: get_term_by('name', 'pa_attribute-color', 'pa_attribute-color); to get the Name/label 
    
                $result = array( $available_variations , $attributes);  // only to see the result you can use var_dump, error_log, etc.
                //...
                //... 
            }elseif ( $product->is_type( 'bundle' ) && class_exists( 'WC_Product_Bundle' ) ) {
                $product = new WC_Product_Bundle( $idProduct );
            }else{
                $product = new WC_Product( $idProduct );
            }
        }
    

    您还可以尝试:

    $product->get_attribute( $key );
    wc_attribute_label($key);
    

    哪里 $key 可以是 ,