NOTE: As of 4.7.1 this isn’t working exactly as published here anymore. Comment thread starts here. I’ll update this once the best way to handle it becomes clear. This is the best I got so far.
For your functions.php file or a functionality plugin:
function cc_mime_types($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');
Without this, SVG files will be rejected when attempting to upload them through the media uploader.
Before WordPress 4.0, you also make them display properly in the Media grid. But that’s broken now. If anyone knows how to fix, let me know!
function fix_svg_thumb_display() {
echo '
td.media-icon img[src$=".svg"], img[src$=".svg"].attachment-post-thumbnail {
width: 100% !important;
height: auto !important;
}
';
}
add_action('admin_head', 'fix_svg_thumb_display');
Thank you!
Thanks alot. I have a Plugin for WordPress with these lines:
Is this the same or does it more than your function?
Haha! That’s my plugin :D
It does the same thing. His is intended to be used within your theme though.
My plugin does a very simple thing :P
It also scans the through SVG files for security risks.
Whats this plugin you made, link us :)
I found ya :) https://wordpress.org/plugins/scalable-vector-graphics-svg/
Sweet plugin btw
Worked like a charm! Just built my first SVG based site with absolutely no image files using WordPress. You’ve been a great help. Thanks so much :)
Can you show me?
Works brilliantly for the upload part, however, the SVG displays huge wherever it gets displayed in WordPress admin, is there a way to prevent this?
Using another snippet I found on here, a simple style injection seems to fix the display of SVGs within the admin area, this fixes the display in the media uploader and the featured image area:
An update on @Steve’s snippet to display your SVG thumbnails in the Media Library grid. This is my preferred method because it does not rely on the thumbnail class. Instead I target images with a
.svg
file extension using the selectorimg[src$=".svg"]
:It doesn’t work :(
Do I just put the code into functions.php file? I do it with a responsive theme, add the code at the end (but I also changed that and added to the end of the code) and it won’t work?
What shall I do?
Bump
After the recent updates to WordPress add_filter() throws up an error message stating it is not defined (depreciated?). Is there an updated method to allow the uploading of SVG into the media gallery?
Thanks!
Solved!
I put the code in the wordpress’s core functions.php file, wrong.
This code needs to be added to the theme’s functions.php, here: /wp-content/themes/[theme]/functions.php
easy mix up.
Is there anyway to disable WordPress from compressing SVG files in the media uploader? I have SVGs down to less than 1KB and wordpress “compresses” them up to 150KB. Hmmm…
How does css-tricks always have an article on exactly what I am trying to do? the best.
Thank you so much for this!
Yes, it allows me to upload the svg images, but I can’t see them in my front, don’t know why :\
I see, it sets the width and height to 1px by default, I can change this manually but not sure how it should be automatically… any ideas?
The issue below has the code you may paste into wp-includes/media.php:
https://core.trac.wordpress.org/ticket/26256
although I have just changed the image_downsize() function in the same file, replace:
with:
you still can not see the thumbnail for svg files, but I have not time to fix that.
THANKYOU
2014 and I find this snippet now only – I must be sleeping under a log!!! Thank you so much :)
How would I resize the svg images?
Doesn’t work with WP 3.8.1
I’m on 3.8.1 right this second and it works for me. Any specifics?
Works in 3.8.1 for me too.
I just found a trick to show the SVG and an alternative Bitmap for older Browsers in an image-Tag on http://lynn.ru/examples/svg/en.html.
And making it responsive on http://www.mediaevent.de/tutorial/svg-responsive.html (german).
I created a plugin using this function but cannot seem for the life of me to get the svg graphic to display.
Its allowing me to upload an svg file but does not display in the front or backend.
Anybody else having this problem?
Maybe this? https://css-tricks.com/snippets/htaccess/serve-svg-correct-content-type/
If you are using Adobe Illustrator CC you have to change the specs to match the article Chris mentions above, otherwise it won’t work. I figured this out through trial and error. Hope this helps and thank you to Chris for this awesome site! :D
What about security? Why are SVG files blocked in the first place by WordPress? Could this mean danger to the sites?
Too much paranoia here. They blocked irregulars. Most wordpress users are non-technical. They are some social media and blog managers so they don’t need things like SVG. Doing these things do not bring any security risks at all. It only makes you more badass than a regular wordpress user.
This isn’t a case of paranoia at all. There are a ton of security risks associated with SVGs, which is the primary reason they’re not allowed by Core.
https://core.trac.wordpress.org/ticket/24251
https://www.owasp.org/images/0/03/Mario_Heiderich_OWASP_Sweden_The_image_that_called_me.pdf
i read all of the comments and this snipped is working well for wordpress 3.8.2
for the use of the feature images on the front-end you have to style the post-image via css:
for fallbacks use svgmagic, cool jqueryplugin
Thanks! Works fine for me.
Also working like a boss.
Mind you: once inserted the svg image wordpress gave it a 1px 1px dimension.. it appeared as a dot. So edit that in the text editor if it happens to you (:
Not working for me, WP 3.8.3.
In functions.php, it works like a charm :)
Still working via WordPress 3.9.2 – and thank you! I wound up using this code:
That third to last line (echo) should be the one at http://pastie.org/9470273. It’s not letting me paste it in this comment box.
Work very well. Thanks saved my time.
Has anyone had any luck getting svg to work with the theme customizer? Use case – allowing end user to upload an SVG logo via the theme customizer.
The stuff above works great for the media uploader, but it’s a no-go via the customizer. SVG files are greyed out and not selectable when trying to upload.
TIA for any insight.
Thanks a LOT …….keep up the good codes come up :) God Bless You :)
Hey!
Thanks for this. Well, everything really. You offer great stuff. I was using this script today and noticed it wasn’t printing the css properly. Anywho… I added to it slightly and seemed to solve the problem for me. The SVGs were not showing correctly in the list view. But with the addition of they do. Maybe this will help others.
Hmmm. that’s odd. I added a before the td and after the closing CSS bracket. Seems like the comment thing filtered that out.
The “Featured Image” display did not work for me until I added another ID.
#postimagediv img[src$=".svg"]
you are right, i found out you can use
Does not work…
Why WP save svg as ‘.png’ file?
If the thumbnails in 4.X still aren’t working, you may need to make sure that the code gets inserted as actual inpage stylesheets. I think the code display isn’t allowing for the proper display of the <style> element which is supposed to follow the opening of the echo.
so it should actually look like this:
NOTE: this only displays in the list view.
you got it gray!
so far this is working well with wordpress 4.0
i added feature image support and removed the ugly border around the images in the media list view.
any news or even solutions about the media grid view?
Legend!
This speaks majorly on uploading as a media. What if I wanted to write SVG directly, or write mathML directly, how can I make wordpress parse it correctly. It auto-changes it to something ugly and takes off all the tags
Why can’t something like this be added to wp-includes/media-template.php in the core… to display vector graphics on the admin side for thumbnail views and attachment displays?
Can someone explain what would be incorrect about doing that? A security risk? Enlighten me!
Hey,
I’ve came across this cool interactive SVG Christmas animations.
Its a Google Chrome Experiment
Please Check it out.
https://ihatetomatoes.net/svg-christmas/
This is to support SVG users
Thanks so much and more power.!
Thanks!! This really helped me a lot :)
I am sure there is a special place in hell for doing what I just did, but it work for what was needed.
Pushing code manually with javascript into the wp media template…
https://gist.github.com/mchiron/860d474afc27018327d9
Solved it!
https://gist.github.com/Lewiscowles1986/44f059876ec205dd4d27
No CSS edits needed in IE(edge), FF(edge) or Chrome(edge), nice leg-work on original everyone, lets bug Mullenweg to include this in core WP for the future!
Only took them a year and a few months to break it…
Basically because of the ‘image/’ prefix in mime type you’ll never get past uploading. WordPress specifically passes all files with this to gd extension
getimagesize
where available.I’ve got a new branch in the git repo that changes to ‘application/xml+svg’ so the file uploads. What then needs to happen is a rename of the mime-type to ‘image/svg+xml’ upon successful upload (looking for a hook now).
It’s really bad that this is the case, but give me a week or so and it’ll be fixed again.
Fixed, merged to master https://github.com/Lewiscowles1986/WordPressSVGPlugin
Also there is now a proposed core patch submitted to allow wordpress to support this out of the box https://core.trac.wordpress.org/ticket/31973, anyone can check it out and if possible do what you can to get it into core (Why is it not already???)
@LewisCowles1
You are a genius!!!
Thanks for this :)
I have taken a little bit of that code and added it to my plugin “SVG Support” https://wordpress.org/plugins/svg-support/ (still to push the latest update to the repository in the next few days) which actually does a little more in that it allows you to style your SVG’s after embedding them inline into your page based on a class.
I have spent hours trying to sort out this thumbnail issue since last year, so thank you kindly for showing this!!!
Cheers
Hi Ben,
Thanks for the heads up and link ;). Glad I could help, it really should be in core, but if you’ve ever visited core, looked at the code, you’ll see why it’s not…
Unfortunately, this seems to be no longer working as of WP version 4.2.2. Maybe they increased their security? I’m getting this message while trying to upload SVG to the media library:
“logo-petco.svg” has failed to upload due to an error
Sorry, this file type is not permitted for security reasons.
Hi Nathan,
I can still upload using the code from this gist, even in 4.2.2…
https://gist.github.com/Lewiscowles1986/44f059876ec205dd4d27
The feedback I got from the WP Core team was taggable formats can be exploited (the irony of WP using HTML & JS was not lost on me), check out the code in that gist, save it in the plugins dir and activate ;)
Lewis – thanks for your reply.
I put your PHP file into my plugins directory, I also have Chris’s above code in my functions.php, and still no luck on uploading SVG files into my media library. I’m stumped. I was able to upload SVG before 4.2.2.
Can I email you over a couple screenshots so I can show you what’s going on?
Hi Nathan,
Screenshots definitely will not help you, or me (or anyone else), in resolving this buddy. Do me a favor, turn off all plugins, except my gist plugin, which needs to be active; switch to a new vanilla theme, and don’t modify it, or core wordpress (if you changed the core, you’ll need to roll-back to a clean install, or re-install); try again. It sounds like either your theme, or one, maybe more of your plugins is causing the issue. I have tested the plugin on quite a few installs of WP, and can confirm it works for standard deploys, standard salient themed & child themed sites, striking theme & child theme sites, 2012, 2014 & 2015 themes, with akismet, google analyticator, Disqus Comment System, all my bespoke client plugins, WooCommerce, maybe some plugins I didn’t install…
Basically the plugin is not very smart, it just modifies the upload types array & some code that is very shodily crammed into DOM by WP.
Also be careful, the gist needs to be copied from GitHub, CSS-Tricks embed in the comment seems bugged (I raised an issue on it earlier).
If the above does not work, get a professional in to help if it’s critical; I am actually unavailable, abroad 1000’s of miles from home right now, so responses could be thin on the ground ;)
Best of luck!
Lewis – you nailed it. Apparently a plugin called “Media Library Assistant” was causing the issue (go figure). I should have tried deactivating all plugins in the first place. Appreciate your thorough help. Have fun abroad :)
lewis, this is great!
now you can see svg-thumbnails is list and grid.view!
also the feature image is working!
still somethings do not work:
– if i add a svg to the tinymce field like a normal picture the height is 1 x 1 px
– the feature image is also not shown up in the front end (you will need css for that)
– no svgmagic support
lets put our plugins together to get the best of both, i’m up for it.
Hi T,
Thanks! To be honest I’ve kinda gone off WP as a platform… The 1px x 1px bug I have a few fixes for. I’ve updated the gist to patch; although you are best off ensuring that all images are in a container to restrict size, and on some android browsers the height is way off using img { width:100%; height:auto; } :(.
I believe CSS-Tricks has an article on it, but it seems at least for now, it’s a complex issue with no perma-fix…
Good luck with the rest of the mods, feel free to stay in touch on here or gist, and link anything cool ;).
Hello,
Thank you Chris. This site pointed me in the right direction for the thousand times.
You’re simply rocking!!
And of course, thanks for the all good people in the comments! :)
Have a nice coding day,
n3nad
This works great!.
Is there any issues with this and the 4.7/4.7.1 wordpress version?. I’ve been trying to make it work but there’s an error massage everytime I try to upload an SVG file.
Thank you, great tip!! I also am having the error with the new WP 4.7.1 update.
there is a change on the mime check in 4.7.1 (wp-includes/functions.php) is there a good snippet to enable svg upload? Before i used :
function custom_mtypes( $m ){
$m['svg'] = 'image/svg+xml';
$m['svgz'] = 'image/svg+xml';
return $m;
}
add_filter( 'upload_mimes', 'custom_mtypes' );
but now this works nomore. i think on line 2514 the
function wp_get_ext_types()
is new
Last time it worked for me was with 4.6.2 WP version.
I’ve even tried installing that version from scratch but it did’n worked
Since 4.7.1 there has been a change in how WP handles mime types. I found this it should work placed in front of the existing code. It’s not ideal but it’s better than the other suggestions I’ve seen.
It should work with the Safe SVG plugin I suggested below yesterday.
Whatever you do don’t use the work around suggesting you include…
in your
wp-config
file. It’s Super insecure!PHP file uploads anyone! :-|
I have tested (my) suggested work around to add SVG support with the Safe SVG plugin and it works fine.
This is still not a great work around, but it’s the best one I have found just now.
I did find this thread on wordpress.org which maybe worth following to see if anyone responds to it.
If anyone has any better suggestions I’d be eager to hear them :-)
Anyone suggesting globally allowing uploads of unfiltered types hasn’t looked at the code fully. The problem is that you upload with mime of type beginning with “image/”, which is passed to GD extension to get dimensions and file info returning false for SVG file. Simply change the “image/svg+xml” to “application/svg+xml”, then later change the mime to the correct one for storage using the hook
wp_check_filetype_and_ext
Looking at your code you’d also need to add
svgz
extension too, but it means not having to make any other uploads insecure to bypass the over-simplistic image information check of 4.7.There is a reference plugin at https://github.com/Lewiscowles1986/WordPressSVGPlugin/ which works for 4.7 with grid, attachment view etc
WordPress 4.7.1 apparently killed the SVG upload described here. This is apparently a bug which should be rectified in v4.7.2. To fix it, add the following code to your functions.php:
Full credit goes to the SVG Support Plugin
I noticed this! Thanks your code fixed the update issue for me!
On 4.7.2 XLSX file uploads are also broken. This code fixed it.
Small optimizations like eliminate a bunch of variables and a function call.
SVG has intrinsic security issues so WordPress doesn’t support SVG upload by default. SVG as a document format is susceptible to Cross-Site Scripting (XSS) attacks as it’s difficult to write an SVG sanitizer that prevents them. Bjørn Johansen does a much better example of explaining why in more depth here: https://bjornjohansen.no/svg-in-wordpress
If you do need to SVG upload support in a WordPress theme Bjørn recommends using the Safe SVG plugin . Although it’s not perfect by any stretch it does at least provide some security. And if it’s for a client job maybe donate and show a little love to it’s developer Daryll Doyle.
If I am doing a small site that I know will only be being used by a couple of experienced users I’ll add the capability via a function a plugin or even add it straight to the
functions.php
.Other times when I am not 100% sure of all the use cases I will suggest to my client to use the Safe SVG plugin.
Either way I suggest adding some documentation to your theme or plugin’s if you use it readme file to highlight the potential dangers and risks of enabling SVG upload in WordPress.
Thank you to Sakin Shrestha for first highlighting this to me.
you simply shouldn’t be allowing unfiltered uploads no matter the reason.
Everything should be explicitly defined even if it’s a little more work for-now. Also the “SVG” is insecure is nonsense!
It suffers no more problems than HTML or XML and all it’s vulns could be patched by browser vendors and good practices (i.e. buying from, in-house producing and using reputable vendors for SVG content).
We Made small alternation to the above code. Now it is working.
add_filter( ‘wp_check_filetype_and_ext’, function($data, $file, $filename, $mimes) {
global $wp_version; if( $wp_version == ‘4.7’ || ( (float) $wp_version < 4.7 ) ) { return $data; }
$filetype = wp_check_filetype( $filename, $mimes );
return [ ‘ext’ => $filetype[‘ext’], ‘type’ => $filetype[‘type’], ‘proper_filename’ => $data[‘proper_filename’] ];
}, 10, 4 );
function cc_mime_types( $mimes ){ $mimes[‘svg’] = ‘image/svg+xml’; return $mimes; } add_filter( ‘upload_mimes’, ‘cc_mime_types’ );
function fix_svg() { echo ‘ .attachment-266×266, .thumbnail img { width: 100% !important; height: auto !important; } ‘; } add_action( ‘admin_head’, ‘fix_svg’ );
and by the way the snippet above will work if you have (simple css) a spacebar between
function fix_svg_thumb_display() {
echo '
td .media-icon img[src$=".svg"], img[src$=".svg"].attachment-post-thumbnail {
width: 100% !important;
height: auto !important;
}
';
}
add_action('admin_head', 'fix_svg_thumb_display');
I don’t wanna sound like a n00b, but did the code from Codepen break everything for you? i can’t even get into wp-admin…
The original code is working again on version 4.7.3! woohoo!!
The thumbnail preview I can’t get to work on WP 4.73
I have been using this plugin https://wordpress.org/plugins/svg-support/
Gives me full control via CSS over the images
Makes SVG Support for the media library
Works with the new Image Widget (WP 4.8-alpha +)
Restricts SVG upload ability to Administrators only
And is Extremely Simple To Use
hi guys, it’s been a while since i looked around here.
as far as i see my snippet still works.
the only 3 things which do not work at the backend are:
– show the svg in media list view
– show the svg in media single view (when clicked on the image)
– show the svg in feature image
as far as i realize it, all the other plugins use javascript to achieve those features.
but, since i like to keep it super light weight, is there a way to do this without any js-coding?
ok, i solved it all by putting the right things together. thanks to lewis and Guenni007.
also it works fine when using svg-images in the normal tinymce editor. the big plus is, it’s super small and comes with png fallback.
i will try to compile a plugin zip and upload it to wordpress as a plugin if that is not to complicated.
only problem now is that when using the new image widget with svg this error appears:
Warning: Illegal string offset ‘height’ in /wp-includes/media.php on line 989 and line 988
any solutions for this are welcome.
Just use this https://wordpress.org/plugins/enable-svg-uploads/
cool, i didn’t know that lewis allready made his own plugin.
anyway it does not work with the new image widget so far (can’t see them in front-end).
besides it has a lot of .json files in it and no png-backfall, so i will stick with mine for a while.
i found out that somehow it’s a resize issue, but no one has a solution for that yet.
Raise an issue (or several) with screenshots, it’ll get patched as long as it’s not theme or plugin specific. Then everyone benefits. As-is I’m not sure I understood your points. https://github.com/Lewiscowles1986/WordPressSVGPlugin. Rolling your own is fine if you’ll stick to it, which Lewis has since 2015 when he launched the gist.
yeah i know the feeling, i developed mine in 2014 as you can see in the timeline but never released it officialy.
i can’t believe that lewis has less than 10 installs where Benbodhi has 100000 – seems quite unfair to me.
I got the media grid thumbnail working by adding a function that adds the dimensions metadata to the svg uploaded. I just put this in my functions.php
Found it in this answer here https://wordpress.stackexchange.com/questions/255687/set-media-metadata-i-e-dimensions-field-on-svg-file-after-extracting-it-wit
The only thing i miss in these approaches to SVG support in WordPress is the title and descriptions functionality in inline SVGs. Would it be possible to read “alternative text” and “description” attributes from media library and insert them into inline SVGs’ respectively elements?
The solution that worked for me was to override the backbone.js template written in the footer of upload.php?mode=grid. This tutorial helped me: https://www.ibenic.com/extending-wordpress-media-uploader-embed-options/.
In the overwriting template (all templates are written in wp-includes/media-template.php, they will be printed to the admin footer) id=”tmpl-attachment” you have to replace the line
<img src="{{ data.icon }}" class="icon" draggable="false" alt="" />
with
<img src="{{ data.size.url }}" class="thumbnail" draggable="false" alt="" />
Are you serious with the second snippet? It just dumps the CSS to admin page!
I had the same error as some of you while uploading svg files on wordpress 5.0.3 through the use of the wp hook, but Enable SVG Uploads works like a charm, in case someone could have the same issue at January 21, 2019.
Cheers man.
Paste both in functions.php
Hi. I can’t upload webp. Did you have any solutions?