Automattic\WooCommerce\Blocks\Utils

ProductGalleryUtils::maybe_generate_intermediate_image()public staticWC 1.0

Generates the intermediate image sizes only when needed.

Method of the class: ProductGalleryUtils{}

No Hooks.

Return

null. Nothing (null).

Usage

$result = ProductGalleryUtils::maybe_generate_intermediate_image( $attachment_id, $size );
$attachment_id(int) (required)
Attachment ID.
$size(string) (required)
Image size.

ProductGalleryUtils::maybe_generate_intermediate_image() code WC 8.9.0

public static function maybe_generate_intermediate_image( $attachment_id, $size ) {
	$metadata   = image_get_intermediate_size( $attachment_id, $size );
	$upload_dir = wp_upload_dir();
	$image_path = '';

	if ( $metadata ) {
		$image_path = $upload_dir['basedir'] . '/' . $metadata['path'];
	}

	/*
	 * We need to check both if the size metadata exists and if the file exists.
	 * Sometimes we can have orphaned image file and no metadata or vice versa.
	 */
	if ( $metadata && file_exists( $image_path ) ) {
		return;
	}

	$image_path     = wp_get_original_image_path( $attachment_id );
	$image_metadata = wp_get_attachment_metadata( $attachment_id );

	// If image sizes are not available. Bail.
	if ( ! isset( $image_metadata['width'], $image_metadata['height'] ) ) {
		return;
	}

	/*
	 * We want to take the minimum dimension of the image and
	 * use that size as the crop size for the new image.
	 */
	$min_size                         = min( $image_metadata['width'], $image_metadata['height'] );
	$new_image_metadata               = image_make_intermediate_size( $image_path, $min_size, $min_size, true );
	$image_metadata['sizes'][ $size ] = $new_image_metadata;

	wp_update_attachment_metadata( $attachment_id, $image_metadata );
}