'Adding multiple images to a product via Woocommerce REST API (within a for loop with varying amounts of pictures per product)
I am trying to create new products for my Woocommerce store but I'm struggling with the images. I am iterating through all the products in my excel sheet with a for loop. In each loop I'm uploading all the pictures of a product to Wordpress. It then returns the image IDs which I add to a list, for example:
img_id_list = [203, 204, 205, 206, 207, 208]
When it comes to defining the product data, I have to attribute the image ID to the product data like this:
product_data = {
"name": name,
"description": description,
"short_description": short_description
"sku": SKU,
"regular_price": selling_price,
"categories": [
{
"id": category}]
"images": [
{
"id": img_id_list[0]
},
{
"id": img_id_list[1]
}
]
}
As you can see, the problem is that I have to create a new "id" attribute within the product_data variable for each image ID. However, not all products in my for loop have the same amount of images (some have 5, while others might have 2). How can I assign all image ID's to the product data when the amount of image ID's varies each loop? Is there a pythonic way to solve this problem?
Solution 1:[1]
I found an answer so i'll just post it here in case someone has the same problem:
You can simply create a function like this:
def idfinder(img_id_list):
locallist = list()
for i in img_id_list:
localdict = {"id": i}
locallist.append(localdict)
return locallist
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mike Wilhelm |
