Search code examples
pythonfor-loopwoocommercewordpress-rest-apiwoocommerce-rest-api

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

  • more pythonic way:

    product_data = {
        ...
        "images": [{"id": id} for id in img_id_list],
        ...
    }