Kevinleary.net, LLC.

SVG Support & Broken Images

A recent update to the popular SVG Support WordPress plugin may cause broken SVG's on your WordPress site.

If your WordPress website has broken or missing SVG images and you have the SVG Support plugin installed your issue can be quickly solve with the following quick fix.

Code to Fix Broken SVG’s

Add the following code to your theme’s functions.php file to solve the issue.

/*
 * Correct SVG <img>'s
 *
 * SVG Support is adding a width and height of 1 on all SVG images in
 * the site.
 */
remove_filter('wp_get_attachment_image_src', 'bodhi_svgs_dimension_fallback', 10);

Why You See Broken Images for *.svg‘s

The SVG Support plugin has a function in it that will:

Fix for division by zero error for SVGs

It specifically sets the width and height attributes to 1 for any SVG’s that don’t provide a set width and height on the <svg> element. It’s not uncommon for this to be the case, many vectors are designed to be flexible and display based on aspect ratio rather than an arbitrary width and height. If you’re having the issue it means that you have SVG’s on your site without these attributes. It’s not an issue though, and the code snippet provided should solve the issue without causing other display issues for you.

I’ve also posted this resolution to WordPress.org in the plugin’s discussion area: All SVGs on site now broken

Bug Source Location in SVG Support

The bug occurs in the function beginning on line 292 of the functions/attachment.php file in the plugin. Here’s a copy of the code for reference:

// fix for division by zero error for SVGs
// proposed by starsis
// https://github.com/WordPress/gutenberg/issues/36603

function bodhi_svgs_dimension_fallback( $image, $attachment_id, $size, $icon ) {

  // only manipulate for svgs
  if ( get_post_mime_type($attachment_id) == 'image/svg+xml' ) {

    if ( !isset($image[1]) or $image[1] === 0 ) {
      $image[1] = 1;
    }
    if ( !isset($image[2]) or $image[2] === 0 ) {
      $image[2] = 1;
    }

  }

  return $image;

}
add_filter( 'wp_get_attachment_image_src', 'bodhi_svgs_dimension_fallback', 10, 4 );

The functionality provided by this chunk of code is based on a recent change to the Gutenberg editor from the core WordPress dev team. It’s reasonable to understand why the plugin author made the change, but regardless it poses issues for many of the websites using the plugin from what I’ve seen around the web. Hopefully this patch helps solve the problem for anyone else experiencing it.

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 15 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.