How to Allow Uploading of SVG Files in WordPress

Update 1/25/17: This is now broken as of WordPress 4.7.1.

WordPress and SVG files

We love using (and should use) SVG—scalable vector graphics—because they are retina-ready, responsive, and easily editable. They never lose quality no matter how you resize them because vector images possess that aspect. If we use SVG, then we don’t have to worry about images or icons being blurry on screens with retina display. For these reasons, we want to upload and use SVG files in WordPress, but WordPress won’t allow us to upload them.

When an SVG upload looks like it succeeded, this error message appears:

Sorry, this file type is not permitted for security reasons.

We’ll study why that happens and a straightforward tweak to enable SVG uploads.

The Problem with SVG Files

Even though SVGs have their advantages, WordPress has a point in denying them in the first place. The ability to upload them can lead to security issues.

Since SVGs are composed of XML code, this will allow cybercriminals to distribute viruses, malware, adware, ransomware, and more malicious software using JavaScript. This can be done by inserting scripts anywhere inside the <svg> tag. It’s that easy.

Even worse, they can code in SQL DELETE commands to damage or destroy databases. According to AppRiver, there was an attack involving zipped SVGs. These files appeared to be innocent documents such as resumes, but after extracting and opening the files, the user would end up downloading the linked malware.

In essence, cybercriminals can use SVGs like Trojan horses to cause lots of trouble.

Allowing SVG Uploads

To allow SVG uploading in the Media Library, place this simple PHP function in your theme’s functions.php file:

<?php
function new_mime_types($mimes) {
  $mimes['svg'] = 'image/svg+xml';
  $mimes['svgz'] = 'image/svg+xml';
  return $mimes;
}
add_filter('upload_mimes', 'new_mime_types');
?>

The code will add permitted mime types for the SVG and its compressed variant SVGZ. This is the most common method without plugins, but you will not see thumbnails for those image types in the Media Library.

Conclusion

If you’re the only registered user and admin on your WordPress site, then you have complete control of how SVGs are used. And if you have staff members or guests creating content and also allow SVG uploads, then you’re confident that everyone won’t use them to do evil. Otherwise, get rid of the snippet immediately.


Posted in: Wordpress