wp_image_matches_ratio( int $source_width, int $source_height, int $target_width, int $target_height )

Helper function to test if aspect ratios for two images match.


Description Description


Parameters Parameters

$source_width

(int) (Required) Width of the first image in pixels.

$source_height

(int) (Required) Height of the first image in pixels.

$target_width

(int) (Required) Width of the second image in pixels.

$target_height

(int) (Required) Height of the second image in pixels.


Top ↑

Return Return

(bool) True if aspect ratios match within 1px. False if not.


Top ↑

Source Source

File: wp-includes/media.php

function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) {
	/*
	 * To test for varying crops, we constrain the dimensions of the larger image
	 * to the dimensions of the smaller image and see if they match.
	 */
	if ( $source_width > $target_width ) {
		$constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width );
		$expected_size = array( $target_width, $target_height );
	} else {
		$constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width );
		$expected_size = array( $source_width, $source_height );
	}

	// If the image dimensions are within 1px of the expected size, we consider it a match.
	$matched = ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 );

	return $matched;
}

Top ↑

Changelog Changelog

Changelog
Version Description
4.6.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

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