根据WooCommerce中的一个默认属性值获取所有产品变体

时间:2017-12-11 08:29:14

标签: php wordpress woocommerce product variations

Following Loic's workflow here我是否可以根据默认值中的一个特定变体获取与产品相关的所有变体。

示例:获取attribute_pa_sizes的所有变体,类似于默认值' s attribute_pa_sizes

echo $variation_values['attributes']['attribute_pa_sizes'] . ': ' . $price ;

1 个答案:

答案 0 :(得分:1)

这可以使用以下代码完成(基于this answer):

<?php 
    global $product;

    $variation_ids = array();
    $targeted_attribute = 'pa_sizes';

    if( $product->is_type('variable') ){
        $default_attributes = $product->get_default_attributes();
        foreach($product->get_available_variations() as $variation_values ){
            foreach($variation_values['attributes'] as $key => $attribute_value ){
                $attribute_name = str_replace( 'attribute_', '', $key );
                if( $attribute_name == $targeted_attribute ){
                    $default_value = $product->get_variation_default_attribute($attribute_name);
                    if( $default_value == $attribute_value ){
                        // We set all related variation IDs in an array
                        $variation_ids[] = $variation_values['variation_id'];
                    }
                }
            }
        }

        if( count( $variation_ids ) > 0 ){
            // Iterating through each variation ID 
            foreach( $variation_ids as $variation_id ){
                // Get the "default" WC_Product_Variation object
                $variation = wc_get_product($variation_id);
                // Get variation attribute values
                $variation_attributte = $variation->get_variation_attributes();
                // Raw output variation attribute values
                echo '<pre>'; print_r($variation_attributte); echo '</pre>';
                // Get the active price
                $price = $variation->get_price();
                // Output price
                echo '<p>Price: ' . $price . '</p>';
            }
        }
    }
?>

经过测试和工作