Automattic\WooCommerce\Internal\CLI\Migrator\Core

WooCommerceProductImporter::import_image_with_mappingprivateWC 1.0

Import image from URL with mapping optimization.

Method of the class: WooCommerceProductImporter{}

No Hooks.

Returns

Int|null. Attachment ID or null on failure.

Usage

// private - for code of main (parent) class only
$result = $this->import_image_with_mapping( $image_url, $alt_text, ?string $original_id, $product_id ): ?int;
$image_url(string) (required)
Image URL.
$alt_text(string)
Alt text for the image.
Default: ''
?string $original_id
.
Default: null
$product_id(int)
Product ID for sideloading.

WooCommerceProductImporter::import_image_with_mapping() code WC 10.8.1

private function import_image_with_mapping( string $image_url, string $alt_text = '', ?string $original_id = null, int $product_id = 0 ): ?int {
	if ( $original_id && isset( $this->migration_data['images_mapping'][ $original_id ] ) ) {
		$attachment_id = $this->migration_data['images_mapping'][ $original_id ];
		if ( wp_attachment_is_image( $attachment_id ) ) {
			return $attachment_id;
		} else {
			unset( $this->migration_data['images_mapping'][ $original_id ] );
		}
	}

	$start_time    = microtime( true );
	$attachment_id = $this->import_image( $image_url, $alt_text, $product_id );
	$duration      = microtime( true ) - $start_time;

	if ( $attachment_id && $original_id ) {
		$this->migration_data['images_mapping'][ $original_id ] = $attachment_id;
	}

	if ( $attachment_id ) {
		$message = sprintf( 'Image uploaded successfully in %.2fs: %s -> %d', $duration, $image_url, $attachment_id );

		if ( $this->import_options['verbose'] ?? false ) {
			\WP_CLI::log( $message );
		}

		wc_get_logger()->info( $message, array( 'source' => 'wc-migrator-images' ) );
	} else {
		$message = sprintf( 'Image upload failed in %.2fs: %s', $duration, $image_url );

		if ( $this->import_options['verbose'] ?? false ) {
			\WP_CLI::warning( $message );
		}

		wc_get_logger()->error( $message, array( 'source' => 'wc-migrator-images' ) );
	}

	return $attachment_id;
}