当前位置: 首页 > 知识库问答 >
问题:

Woocommerce产品变体给出错误:-对字符串调用成员函数get_name()

贺乐意
2023-03-14

我想要做的是保存一个新的变体,但在保存时,它会对String上的成员函数get_name()抛出一个错误调用;正在创建变体,但没有任何属性值。

public static function create_product_variants($id,$product,$variant_data){
        
        for($i=0; $i< count($variant_data); $i++){
            $variant = new WC_Product_Variation();
            $variant->set_parent_id($id);
            
            foreach($variant_data[$i] as $key => $value){
                if($key == 'attribute_name'){
                    $attribute_name = $value;
                }
                if($key == 'variant'){
                    if(gettype($value) == 'string'){
                        $variants = [$value];
                    }else{
                        $variants = $value;
                    }   
                }
            }
            if(count($variants) == count($attribute_name)){
                $variant_attributes = array();
            
                for($j=0; $j< count($variants); $j++){
                    $variant_attributes[$attribute_name[$j]] = $variants[$j];
                }
                $variant->set_attributes($variant_attributes);
            }
            $id = $variant->save();
            
        }
}

通过$VARIANT_DATA的数据是:

[
    {
      attribute_name: ["Color","Size"]
      price: "10"
      quantity: "20"
      variant: ["red","24"]
    }
]

$ID是product_id

共有1个答案

朱海超
2023-03-14

做得很简单,就像

public static function create_product_variants($id,$product,$variant_data){
        
    foreach ($variant_data as $object){
        $variant = new WC_Product_Variation();
        $variant->set_parent_id($product->get_id());
        $attributes = array_combine($object->attribute_name, $object->variant)
        $variant->set_attributes($attributes);
        $variant->save();
    }
    
}

如果对象是

[
    {
      attribute_name: ["Color","Size"]
      price: "10"
      quantity: "20"
      variant: ["red","24"]
    }
]
 类似资料: