I am trying unsuccessfully to delete all the products related with a woocommerce order in order to update this order with new products.
To do this I guess the 1st step is to delete all the line_items of the specific order and make a put to update.
The 2nd step is again to make a put but with the new products this time in the position of line_items.
Has anyone any idea what’s going wrong with my code?
In this post , https://github.com/woocommerce/woocommerce/issues/22177, I saw that I have to put in the quantity field of every product in my line_items the value of 0, but it doesn’t work.
Here is my code:
def update_woocommerce_order_products_with_quantities(wcapi,order,oldWooOrderHasProducts):
fetched_products=Woo_Order_Has_Products.objects.filter(woo_order_id=order_id)
#FIRST I HAVE TO DELETE THE PRODUCTS OF THE WOOCOMMERCE ORDER
for oldWooOrderHasProduct in oldWooOrderHasProducts:
data = {
"line_items": [
{
"id": str(oldWooOrderHasProduct.wholesale_product.pid),
"quantity": 0,
}
]
}
wcapi.put("orders/"+str(oid),data).json()
#for every product update the price and quantity
for fetched_product in fetched_products:
data = {
"line_items": [
{
"id": str(fetched_product.wholesale_product.pid),
"quantity": str(fetched_product.quantity),
"price": str(fetched_product.price)
}]
}
wcapi.put("orders/"+str(oid),data).json()
2
Answers
In order to delete the existing products in line_items for an order you have to:
1) fetch from the woocommerce rest api the line_items. The oid is the order's id.
2) create the data dictionary based on the
line_items
key. The important thing is putting the quantity of every product inline_items
equals to zero.3) Update the data through the woocommerce rest api.
Here:
You are rebinding
data
on each iteration, so only the last value is used for the API call. You want to create thedata
dict outside the loop and only append toline_items
within the loop:And you have the same issue for the second loop.