wp_image_matches_ratio() WordPress Function

This function allows you to check if an image matches the specified width and height. You can use this function to make sure that an image is the correct size before you use it on your website. This is especially useful if you are using images from a third-party source and you want to make sure they are the right size. To use this function, specify the width and height of the image you want to check. The function will then return a boolean value (true or false) depending on whether or not the image matches the specified size.

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.


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

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


Top ↑

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 = ( wp_fuzzy_number_match( $constrained_size[0], $expected_size[0] ) && wp_fuzzy_number_match( $constrained_size[1], $expected_size[1] ) );

	return $matched;
}


Top ↑

Changelog

Changelog
VersionDescription
4.6.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More