WooCommerce REST API: Create Product with Images
I am starting to have more and more tutorials about REST API on my blog which is for sure because I am doing some work with my crossposting plugin.
Today is another one where I am going to share with you a simple code example how you can add Product image and Product gallery images when creating a product with REST API.
Just in case I mean these things:
Either you create a product with
/wc/v3/products/ or update and existing one with
/wc/v3/products/<id> endpoint, in both cases you can pass an array of images to the body of the request. Let’s look at the example and then I am going to explain it to you in details.
$request = wp_remote_request( 'https://your-website/wp-json/wc/v3/products', array( 'method' => 'POST', 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( "$key:$secret" ) ), 'body' => array( 'name' => 'Test Product 123', 'regular_price' => '2100.99', 'images' => array( // image 1 array( // the first one is for Product image (Featured image) 'id' => 5, ), // image 2 array( 'id' => 5491, ), // image 3 array( 'src' => 'https://rudrastyh.com/wp-content/uploads/2022/12/at-third-place.jpg', 'name' => 'Misha is working in Athens', 'alt' => 'Misha Rudrastyh is working in Athens', ) ) ) ) );
Some notes related to the code above:
- First of all, I would like to remind you that for
$secretyou can use an application password or create a consumer key and consumer secret in WooCommerce settings.
- The first image passed to
imagesarray is always going to be used as a main product image (featured image), all the rest go to product gallery.
- There are also two options how you can pass an image into the request – you can use any existing image ID (on Site 2) or you can provide a full URL to the image file, in this case WooCommerce will parse it and add it to media library itself.
One more thing – it is kind of strict API request, so if you provide something wrong into
images array, then the product is not going to be created at all. So always double check that you’re providing correct image IDs or URLs.
Below are the common errors:
|#123 is an invalid image ID.|
|Error getting remote image <URL>. Error: Not Found|
|Error getting remote image <URL>. Error: A valid URL was not provided.|