What i am trying to do is save a new variation but when saving it, it throws an error
Call to a member function get_name() on string;
The variations are being created but without any attribute value.
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();
}
}
The data passing through $variant_data
is like:
[
{
attribute_name: ["Color","Size"]
price: "10"
quantity: "20"
variant: ["red","24"]
}
]
$id
is product_id
2
Answers
Do it simple like
if the object is
There are some complications and mistakes in your code. Instead try the following revisited code:
It should better work.
The variations will be created/saved, the the method
get_name()
should not throw any error this time.