10up / safe-svg

Enable SVG uploads and sanitize them to stop XML/SVG vulnerabilities in your WordPress website.
https://wordpress.org/plugins/safe-svg/
GNU General Public License v2.0
266 stars 31 forks source link

SVG height and width attributes #6

Open jeremymoore opened 5 years ago

jeremymoore commented 5 years ago

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;
}```
darylldoyle commented 3 years ago

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.