@@ -130,8 +130,7 @@ protected function prepare_object_for_database( $request, $creating = false ) {
130130 // Thumbnail.
131131 if ( isset ( $ request ['image ' ] ) ) {
132132 if ( is_array ( $ request ['image ' ] ) ) {
133- $ image = $ request ['image ' ];
134- $ variation = $ this ->set_product_images ( $ variation , array ( $ image ) );
133+ $ variation = $ this ->set_variation_image ( $ variation , $ request ['image ' ] );
135134 } else {
136135 $ variation ->set_image_id ( '' );
137136 }
@@ -339,6 +338,48 @@ protected function get_image( $variation ) {
339338 return ;
340339 }
341340
341+ /**
342+ * Set variation image.
343+ *
344+ * @throws WC_REST_Exception REST API exceptions.
345+ * @param WC_Product_Variation $variation Variation instance.
346+ * @param array $image Image data.
347+ * @return WC_Product_Variation
348+ */
349+ protected function set_variation_image ( $ variation , $ image ) {
350+ $ attachment_id = isset ( $ image ['id ' ] ) ? absint ( $ image ['id ' ] ) : 0 ;
351+
352+ if ( 0 === $ attachment_id && isset ( $ image ['src ' ] ) ) {
353+ $ upload = wc_rest_upload_image_from_url ( esc_url_raw ( $ image ['src ' ] ) );
354+
355+ if ( is_wp_error ( $ upload ) ) {
356+ if ( ! apply_filters ( 'woocommerce_rest_suppress_image_upload_error ' , false , $ upload , $ variation ->get_id (), array ( $ image ) ) ) {
357+ throw new WC_REST_Exception ( 'woocommerce_variation_image_upload_error ' , $ upload ->get_error_message (), 400 );
358+ }
359+ }
360+
361+ $ attachment_id = wc_rest_set_uploaded_image_as_attachment ( $ upload , $ variation ->get_id () );
362+ }
363+
364+ if ( ! wp_attachment_is_image ( $ attachment_id ) ) {
365+ throw new WC_REST_Exception ( 'woocommerce_variation_invalid_image_id ' , sprintf ( __ ( '#%s is an invalid image ID. ' , 'woocommerce ' ), $ attachment_id ), 400 );
366+ }
367+
368+ $ variation ->set_image_id ( $ attachment_id );
369+
370+ // Set the image alt if present.
371+ if ( ! empty ( $ image ['alt ' ] ) ) {
372+ update_post_meta ( $ attachment_id , '_wp_attachment_image_alt ' , wc_clean ( $ image ['alt ' ] ) );
373+ }
374+
375+ // Set the image name if present.
376+ if ( ! empty ( $ image ['name ' ] ) ) {
377+ wp_update_post ( array ( 'ID ' => $ attachment_id , 'post_title ' => $ image ['name ' ] ) );
378+ }
379+
380+ return $ variation ;
381+ }
382+
342383 /**
343384 * Get the Variation's schema, conforming to JSON Schema.
344385 *
0 commit comments