Skip to content

SVG height and width attributes #6

@jeremymoore

Description

@jeremymoore

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;
}```

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Projects

    Status

    Backlog

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions