Home > Software engineering >  Add/Set product Images and gallery images programmatically
Add/Set product Images and gallery images programmatically

Time:03-25

I'm getting data from jSON file and trying to setup the images for a product, My goal is - need to develop a way to extract/download images from JSON responses and set images to related product //$product_data is getting the response from Json

$product_data = $_REQUEST['data'];
$product = new WC_Product_Simple();
$product->set_name( $product_data['Title'] ); // it's working
$product->set_status( 'publish' );
$product->save();

If it has multiple images that need to be assigned to a product, the first image need to assign as the featured image/thumbnail, and then assign the rest of the images as the product gallery thumbnails.

jSON response of one product

{ "SKU": "0000000", "Title": "Malt Scotch Whisky", "Image1":

"https://images.skulibrary.com/media/sys_master/hfa/he9/9712207298590.jpg?response-content-disposition=inline;filename=DIAG-5000281045160-1.jpg", "Image2": "https://images.skulibrary.com/media/sys_master/hfa/he9/9712207298590.jpg?response-content-disposition=inline;filename=DIAG-5000281045160-1.jpg", "Image3": "https://images.skulibrary.com/media/sys_master/hfa/he9/9712207298590.jpg?response-content-disposition=inline;filename=DIAG-5000281045160-1.jpg", "Image7": "https://images.skulibrary.com/media/sys_master/hbf/hd5/9712208150558.jpg?response-content-disposition=inline;filename=DIAG-5000281045160-7.jpg" }

CodePudding user response:

$product_images = [];
            $count = 0;
            foreach($product_data as $product_key => $product_value):
                if (strpos($product_key, 'Image') !== false):

                    $product_img_upload = wc_rest_upload_image_from_url(esc_url_raw($product_value));
                    $product_img_id = wc_rest_set_uploaded_image_as_attachment($product_img_upload, $product_data);

                    // Add image ID to array.
                    $product_images[] = $product_img_id;

                    $count  ;

                endif;
            endforeach;

            if (!empty( $product_images ) ) {
                $product->set_image_id( $product_images[0] );
                array_shift($product_images);
                $product->set_gallery_image_ids( $product_images);
            }
  • Related