How to programmatically set product image from an URL with Woocommerce ?
Upload an image to a product with a UI in woocommerce
is very easy but in PHP it’s more difficult.
So for the need that i’ve to connect Pimcore to Woocommerce, I must import product catalog into Woocommerce by an interface.
So how to upload the image from an url ?
In first you need to have your product ID or variation id and get it in your code.
If your are not familiar with product and variation, a product is a collection of variation, in other term, a car can be in blue,black or red. The colors are the variations and the product is the car.
For this post, i will use 1234 for my product variation id.
$product = new WC_Product_Variation("1234");
After that you need in first to download your image into your local filesystem
In my example I save the logo of my website as logo.png but you should adapt to the correct mimetype and name of your file.
file_put_contents( "logo.png", file_get_contents("https://micka39.info/logo.png");
Next we will need to create an array with a name (the name of the file) and a tmp_name that correspond to the path of the file previously downloaded.
$file = array();
$file['name'] = 'logo';
$file['tmp_name'] = "logo.png" ;
To finish we will use the media_handle_sideload
function to save our file with our product.
After we set the image id returned by the function into the product object and we save the object.
$imageId = media_handle_sideload($file, $product->get_id());
$product->set_image_id($imageId);
unlink(ABSPATH . "photo_pack.png");
If you want to run this job in a cron for a daily update of your catalog, do not forget to delete the old image with wp_delete_attachment
!
if(is_numeric($product->get_image_id()))
{
wp_delete_attachment($product->get_image_id(),true);
}