【问题标题】:Get all the values from the attributes set in a variable product从变量产品中设置的属性中获取所有值
【发布时间】:2023-03-21 08:51:01
【问题描述】:

在 WooCommerce 中,我试图独立地获取变量产品的所有值。

例如:
我有属性大小。 尺码有三个值:尺码 S、尺码 M 和尺码 L。
如果产品具有所有尺寸选项,我想在输出中看到该产品三次:

  • 一次 S 码,
  • M码一次
  • 一次是 L 码。

通过以下代码,我可以看到我有哪些变体。此外,不幸的是我没有来。

private function readOptions($product) {
    $variations = $product->get_children();
    foreach ($variations as $variation) {
        $single_variation=new WC_Product_Variation($variation);
        $this->doLog(print_r($single_variation->get_variation_attributes(), true));
    }              
}

有人知道怎么做吗?

谢谢。

【问题讨论】:

    标签: php wordpress woocommerce attributes variations


    【解决方案1】:

    我在这里得到了你的功能代码(评论很好)

    private function readOptions($product) {
    
        // Get all attributes & values set in the product (product variations)
        $variation_attributes = $product->get_variation_attributes();
    
        // iterating through each attribute
        foreach ($variation_attributes as $attribute_slug => $attribute_slug_values){
    
            // Getting the attribute object (the taxonomy object)
            $attribute_obj = get_taxonomy( $attribute_slug ); // Attribute name: $attribute_obj->label
    
            // Iterating through each attribute values set in the product
            foreach($attribute_slug_values as $attribute_slug_value){
    
                // Getting the object of the term value (and the name: $attr_value_obj->name)
                $attr_value_obj = get_term_by( 'slug', $attribute_slug_value, $attribute_slug );
    
                // Output the names of the product, the attribute and the value
                echo '<p>Product "'.$product->get_title().'" has attribute "'.$attribute_obj->label.'" with value "'.$attr_value_obj->name.'"</p>';
            }
        }          
    }
    

    你会得到你所期望的。

    这里的输出只是一个示例,但您会得到产品中设置的每个属性和值:
    产品 + 一个属性 + 一个值 (对于其中设置的所有属性值)。

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 2016-05-10
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      相关资源
      最近更新 更多