Automattic\WooCommerce\Internal\CLI\Migrator\Core
WooCommerceProductImporter::handle_product_images
Handle product images using product object methods.
Method of the class: WooCommerceProductImporter{}
No Hooks.
Returns
null. Nothing (null).
Usage
// private - for code of main (parent) class only $result = $this->handle_product_images( $product, $images_data ): void;
- $product(WC_Product) (required)
- The product object.
- $images_data(array) (required)
- Standardized image data from mapper.
WooCommerceProductImporter::handle_product_images() WooCommerceProductImporter::handle product images code WC 10.7.0
private function handle_product_images( WC_Product $product, array $images_data ): void {
if ( empty( $images_data ) ) {
return;
}
$gallery_ids = array();
$featured_id = null;
$product_id = $product->get_id();
$processed_count = 0;
foreach ( $images_data as $index => $image ) {
if ( $processed_count >= $this->import_options['max_images_per_product'] ) {
break;
}
$original_id = $image['original_id'] ?? null;
$image_url = $image['src'] ?? null;
$image_alt = $image['alt'] ?? '';
$is_featured = $image['is_featured'] ?? ( 0 === $index );
if ( empty( $original_id ) || empty( $image_url ) ) {
wc_get_logger()->warning( 'Skipping image: Missing original ID or URL.', array( 'source' => 'wc-migrator' ) );
continue;
}
if ( isset( $this->migration_data['images_mapping'][ $original_id ] ) && wp_attachment_is_image( $this->migration_data['images_mapping'][ $original_id ] ) ) {
$attachment_id = $this->migration_data['images_mapping'][ $original_id ];
} else {
if ( ! $product_id ) {
$product_id = $product->save();
if ( ! $product_id ) {
wc_get_logger()->warning( "Skipping image upload {$original_id}: Could not get product ID before sideloading.", array( 'source' => 'wc-migrator' ) );
continue;
}
}
$start_time = microtime( true );
$image_desc = $image_alt ? $image_alt : $product->get_name();
$attachment_id = $this->import_image( $image_url, $image_alt, $product_id );
$duration = microtime( true ) - $start_time;
if ( is_wp_error( $attachment_id ) ) {
wc_get_logger()->error( "Error uploading {$image_url}: " . $attachment_id->get_error_message() . " (Duration: {$duration}s)", array( 'source' => 'wc-migrator' ) );
continue;
}
if ( ! $attachment_id ) {
wc_get_logger()->warning( "Image upload failed for {$image_url} (Duration: {$duration}s)", array( 'source' => 'wc-migrator' ) );
continue;
}
$this->migration_data['images_mapping'][ $original_id ] = $attachment_id;
if ( $image_alt ) {
update_post_meta( $attachment_id, '_wp_attachment_image_alt', $image_alt );
}
}
if ( $is_featured ) {
$featured_id = $attachment_id;
} else {
$gallery_ids[] = $attachment_id;
}
++$processed_count;
++$this->import_stats['images_processed'];
}
if ( $featured_id ) {
$product->set_image_id( $featured_id );
}
if ( ! empty( $gallery_ids ) ) {
$product->set_gallery_image_ids( array_unique( $gallery_ids ) );
}
}