Automattic\WooCommerce\Internal\CLI\Migrator\Core
WooCommerceProductImporter::import_image
Import image from URL.
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( $image_url, $alt_text, $product_id ): ?int;
- $image_url(string) (required)
- Image URL.
- $alt_text(string)
- Alt text for the image.
Default:'' - $product_id(int)
- Product ID for sideloading.
WooCommerceProductImporter::import_image() WooCommerceProductImporter::import image code WC 10.7.0
private function import_image( string $image_url, string $alt_text = '', int $product_id = 0 ): ?int {
if ( $this->import_options['dry_run'] ) {
return null;
}
if ( ! $this->import_options['skip_duplicate_images'] ) {
$existing_attachment = $this->get_attachment_by_url( $image_url );
if ( $existing_attachment ) {
return $existing_attachment;
}
}
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
add_filter( 'http_request_timeout', array( $this, 'set_image_download_timeout' ) );
add_filter( 'http_request_args', array( $this, 'optimize_http_request_args' ) );
add_filter( 'image_sideload_extensions', array( $this, 'add_avif_support_to_sideload' ) );
try {
$attachment_id = media_sideload_image( $image_url, $product_id, null, 'id' );
if ( is_wp_error( $attachment_id ) ) {
$message = sprintf( 'Image import failed for URL %s: %s', $image_url, $attachment_id->get_error_message() );
if ( $this->import_options['verbose'] ?? false ) {
\WP_CLI::warning( $message );
}
wc_get_logger()->error( $message, array( 'source' => 'wc-migrator-images' ) );
return null;
}
if ( $alt_text ) {
update_post_meta( $attachment_id, '_wp_attachment_image_alt', $alt_text );
}
return $attachment_id;
} finally {
remove_filter( 'http_request_timeout', array( $this, 'set_image_download_timeout' ) );
remove_filter( 'http_request_args', array( $this, 'optimize_http_request_args' ) );
remove_filter( 'image_sideload_extensions', array( $this, 'add_avif_support_to_sideload' ) );
}
}