WC_Regenerate_Images::maybe_resize_image( array $image, int $attachment_id, string|array $size, bool $icon )

Check if we should maybe generate a new image size if not already there.


Description Description


Parameters Parameters

$image

(Required) Properties of the image.

$attachment_id

(Required) Attachment ID.

$size

(Required) Image size.

$icon

(Required) If icon or not.


Top ↑

Return Return

(array)


Top ↑

Source Source

File: includes/class-wc-regenerate-images.php

	public static function maybe_resize_image( $image, $attachment_id, $size, $icon ) {
		if ( ! apply_filters( 'woocommerce_resize_images', true ) ) {
			return $image;
		}

		// Use a whitelist of sizes we want to resize. Ignore others.
		if ( ! $image || ! in_array( $size, apply_filters( 'woocommerce_image_sizes_to_resize', array( 'woocommerce_thumbnail', 'woocommerce_gallery_thumbnail', 'woocommerce_single', 'shop_thumbnail', 'shop_catalog', 'shop_single' ) ), true ) ) {
			return $image;
		}

		$target_size      = wc_get_image_size( $size );
		$image_width      = $image[1];
		$image_height     = $image[2];
		$ratio_match      = false;
		$target_uncropped = '' === $target_size['width'] || '' === $target_size['height'] || ! $target_size['crop'];

		// If '' is passed to either size, we test ratios against the original file. It's uncropped.
		if ( $target_uncropped ) {
			$full_size = self::get_full_size_image_dimensions( $attachment_id );

			if ( ! $full_size || ! $full_size['width'] || ! $full_size['height'] ) {
				return $image;
			}

			$ratio_match = wp_image_matches_ratio( $image_width, $image_height, $full_size['width'], $full_size['height'] );
		} else {
			$ratio_match = wp_image_matches_ratio( $image_width, $image_height, $target_size['width'], $target_size['height'] );
		}

		if ( ! $ratio_match ) {
			$full_size = self::get_full_size_image_dimensions( $attachment_id );

			if ( ! $full_size ) {
				return $image;
			}

			// Check if the actual image has a larger dimension than the requested image size. Smaller images are not zoom-cropped.
			if ( $image_width === $target_size['width'] && $full_size['height'] < $target_size['height'] ) {
				return $image;
			}

			if ( $image_height === $target_size['height'] && $full_size['width'] < $target_size['width'] ) {
				return $image;
			}

			// If the full size image is smaller both ways, don't scale it up.
			if ( $full_size['height'] < $target_size['height'] && $full_size['width'] < $target_size['width'] ) {
				return $image;
			}

			return self::resize_and_return_image( $attachment_id, $image, $size, $icon );
		}

		return $image;
	}


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.