0

Auto-Scale Image Attributes in WordPress

Posted in PHP

We’ve been having no end to issues with image scaling in WordPress where an administrator uploads a ridiculously large image and it appears stretched vertically in Internet Explorer.

I looked into this and discovered WordPress was automatically adding width and height attachments onto the inserted image in the admin. This is generally fine as all modern browsers will scale accordingly for smaller windows…but then we have Internet Explorer which will just retardedly scale width but not height resulting in massively stretched images.

The approach I ended up taking to fix it was to scale the automatically generated width and height attributes on the image down before the HTML is inserted into the post in admin. This can be accomplished with the following snippet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
add_filter( 'post_thumbnail_html', 'flyn_apply_max_image_dimenions', 10 );
add_filter( 'image_send_to_editor', 'flyn_apply_max_image_dimenions', 10 );
function flyn_apply_max_image_dimenions( $html ) {
	ini_set('display_errors', true);
	preg_match('/width="(\d+)"\s/', $html, $wmatches);
	preg_match('/height="(\d+)"\s/', $html, $hmatches);
 
	if ( !empty($wmatches[1]) && !empty($hmatches[1]) )
	{
		list($width, $height) = boilerplate_scale_inside($wmatches[1], $hmatches[1], 630, 9999);
		$html = str_replace('width="'.$wmatches[1].'"', 'width="'.$width.'"', $html);
		$html = str_replace('height="'.$hmatches[1].'"', 'height="'.$height.'"', $html);
	}
 
	return $html;
}
 
function flyn_scale_inside( $width, $height, $into_width, $into_height )
{
	$ratio = $into_width / $width;
 
	$width = $into_width;
	$height *= $ratio;
 
	if ( $height > $into_height )
	{
		$ratio = $into_height / $height;
		$height = $into_height;
		$width *= $ratio;
	}
 
	return array($width, $height);
}

Set your maximum width however you please (I’m using 630px in the example above). I chose a height of 9999 so the image would always be scaled nicely to my themes maximum width.