Umer
Umer

Reputation: 43

Add/Set product Images and gallery images programmatically

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.

Upvotes: 1

Views: 2916

Answers (1)

Newbee
Newbee

Reputation: 56

$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);
            }

Upvotes: 3

Related Questions