WC_REST_Products_V1_Controller::set_product_images()protectedWC 1.0

Set product images.

Method of the class: WC_REST_Products_V1_Controller{}

Return

WC_Product.

Usage

// protected - for code of main (parent) or child class
$result = $this->set_product_images( $product, $images );
$product(WC_Product) (required)
Product instance.
$images(array) (required)
Images data.

WC_REST_Products_V1_Controller::set_product_images() code WC 8.6.1

protected function set_product_images( $product, $images ) {
	if ( is_array( $images ) ) {
		$gallery = array();

		foreach ( $images as $image ) {
			$attachment_id = isset( $image['id'] ) ? absint( $image['id'] ) : 0;

			if ( 0 === $attachment_id && isset( $image['src'] ) ) {
				$upload = wc_rest_upload_image_from_url( esc_url_raw( $image['src'] ) );

				if ( is_wp_error( $upload ) ) {
					if ( ! apply_filters( 'woocommerce_rest_suppress_image_upload_error', false, $upload, $product->get_id(), $images ) ) {
						throw new WC_REST_Exception( 'woocommerce_product_image_upload_error', $upload->get_error_message(), 400 );
					} else {
						continue;
					}
				}

				$attachment_id = wc_rest_set_uploaded_image_as_attachment( $upload, $product->get_id() );
			}

			if ( ! wp_attachment_is_image( $attachment_id ) ) {
				throw new WC_REST_Exception( 'woocommerce_product_invalid_image_id', sprintf( __( '#%s is an invalid image ID.', 'woocommerce' ), $attachment_id ), 400 );
			}

			if ( isset( $image['position'] ) && 0 === absint( $image['position'] ) ) {
				$product->set_image_id( $attachment_id );
			} else {
				$gallery[] = $attachment_id;
			}

			// Set the image alt if present.
			if ( ! empty( $image['alt'] ) ) {
				update_post_meta( $attachment_id, '_wp_attachment_image_alt', wc_clean( $image['alt'] ) );
			}

			// Set the image name if present.
			if ( ! empty( $image['name'] ) ) {
				wp_update_post( array( 'ID' => $attachment_id, 'post_title' => $image['name'] ) );
			}
		}

		if ( ! empty( $gallery ) ) {
			$product->set_gallery_image_ids( $gallery );
		}
	} else {
		$product->set_image_id( '' );
		$product->set_gallery_image_ids( array() );
	}

	return $product;
}