safe-svg icon indicating copy to clipboard operation
safe-svg copied to clipboard

SVG height and width attributes

Open jeremymoore opened this issue 6 years ago • 2 comments

Hi @darylldoyle

What are your thoughts on trying to assign the default height and width attributes based on the image size used in the wp_get_attachment_image() function?

echo wp_get_attachment_image( $svg_id, [78, 78], true, [
     'class' => 'img-fluid',
     'alt' => 'icon',
] );

For example, when I use the above in my template with your plugin activated my SVG is loaded with the height and width attributes set to the images default size. I, however, would like the height and width to be 78x78.

I ended up using the following filter in my theme to work around the issue... but i think this would be worth considering incorporating into the plugin.

add_filter( 'wp_get_attachment_image_attributes', 'wwc_fix_direct_image_output', 11, 3 );
function wwc_fix_direct_image_output( $attr, $attachment, $size = 'thumbnail' ) {

	// If we're not getting a WP_Post object, bail early.
	// @see https://wordpress.org/support/topic/notice-trying-to-get-property-id/
	if ( ! $attachment instanceof WP_Post ) {
		return $attr;
	}

	$mime = get_post_mime_type( $attachment->ID );
	if ( 'image/svg+xml' === $mime ) {
		$default_height = 100;
		$default_width  = 100;

		$size = image_downsize($attachment->ID, $size);
		
		if (is_array($size) && sizeof($size) >= 3) {
			$attr['height'] = $size[2];
			$attr['width']  = $size[1];
		}
	}

	return $attr;
}```

jeremymoore avatar Jul 31 '19 17:07 jeremymoore

Thanks for the info @jeremymoore.

I think this could be a great enhancement moving forward, especially taking CLS into account now.

@jeffpaul this could work by wrapping lines 471-476 in a conditional that checks for the full size and otherwise returning the size requested as above.

We should also take into account that $size may be an array rather than a string with a named size.

darylldoyle avatar Aug 31 '21 08:08 darylldoyle