Programmatically add product variants via API #932
-
Hi there! I am working on an auto product importer that runs every night for CSV files containing products. I am running into a problem: I tried to Programmatically add product variants via API like so. $product->set('product_variants', $product_variants_array); But the variants are not added. However, if I use a double underscore for the key name (or any other random string) it is added. And if I then in de database rename product__variants to product_variants (single underscore) it DOES work, and the variants appear in the CP. $product->set('product__variants', $product_variants_array); Is there a reason for this behavior? I noticed something similar when I tried where I tried to execute $product->set('site') where $product->set('somerandomstring') works fine. Can I not overwrite default keys maybe? For now after finishing my product import, I use a replace query to change product__variants to product_variants (and dan it all works) but this is not ideal and I am trying to understand why this is happening ;-) I am a bit stuck here. Would greatly appreciate some help. Mark |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
Product Variants are special - you can't set them in the same way you can any other field. You need to use the specific When you set the variants, you need to provide an array for both the options & the individual variants. Make sure you have a variant for each of the combinations. You can set the options & variants like this: $product->productVariants([
'variants' => [
['name' => 'Colour', 'values' => ['Red', 'Green', 'Blue']],
['name' => 'Size', 'values' => ['Small', 'Medium']]
],
'options' => [
[
'key' => 'Red_Small',
'variant' => 'Red, Small',
'price' => 1599,
],
[
'key' => 'Red_Medium',
'variant' => 'Red, Medium',
'price' => 2950,
],
// Green_Small
// Green_Medium
// Blue_Small
// Blue_Medium
],
]); Hopefully that's helpful, at least somewhat. |
Beta Was this translation helpful? Give feedback.
Product Variants are special - you can't set them in the same way you can any other field. You need to use the specific
productVariants
method.When you set the variants, you need to provide an array for both the options & the individual variants. Make sure you have a variant for each of the combinations.
You can set the options & variants like this: