DEV Community

Daniel Coturel
Daniel Coturel

Posted on

Get list of WooCommerce products and variations

Hi people. I just did something with JavaScript in a rush, and I would like to see how other people would solve it. Just to compare and because I'm not that good at JavaScipt, I think the answers would be enriching.

They gave me a WooCommerce website with products and variations loaded, and I needed to make a list to do other things on my ERP. The list should have:
1) Product ID
2) Variation ID
3) Variation SKU

I had to use 2 WooCommerce endpoints:

/wp-json/wc/v2/products

This lists all products. Every product has an id field

/wp-json/wc/v2/products//variations

This lists all variations of a given product id. Every variation has an id field and a sku field.

So, that's the challenge, get that list to save it as a CSV file. How would you do that?

Saludos,

Top comments (1)

Collapse
 
theoutlander profile image
Nick Karnik

This is a general design problem.

If I were calling this from a frontend where I had an intermediate server, I would create a single endpoint on my server side which would call the other two URL's. Then, I would aggregate everything and return a response. In addition, I would make it somewhat flexible so I could pass it the type of format I want the data returned in. For instance {host}/api/products/variations?format=csv.

If this were in the backend, you can do it similarly with a function call that would make a call to the two endpoints and merge the data.

On the other hand, if I were calling WooCommerce directly from my frontend, I would create a function as mentioned earlier and fetch the data from both the endpoints and aggregate it. You can use something like Promise.all to accomplish that.