Allow SVG through WordPress Media Uploader

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');

Comments

  1. User Avatar
    JamesonLewis3rd
    Permalink to comment#

    Thank you!

  2. User Avatar
    Julian
    Permalink to comment#

    Thanks alot. I have a Plugin for WordPress with these lines:

    _enable_svg_mime_type();
        }
    
        private function _enable_svg_mime_type() {
            add_filter( 'upload_mimes', array( &$this, 'allow_svg_uploads' ) );
        }
    
        public function allow_svg_uploads( $existing_mime_types = array() ) {
            return $this->_add_mime_type( $existing_mime_types );
        }
    
        private function _add_mime_type( $mime_types ) {
            $mime_types[ 'svg' ] = 'image/svg+xml';
    
            return $mime_types;
        }
    
    }
    
    if ( class_exists( 'scalable_vector_graphics' ) and ! isset( $scalable_vector_graphics ) ) {
        $scalable_vector_graphics = new scalable_vector_graphics();
        $scalable_vector_graphics->execute();
    }
    
    ?>
    

    Is this the same or does it more than your function?

  3. User Avatar
    Karl
    Permalink to comment#

    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 :)

  4. User Avatar
    Steve
    Permalink to comment#

    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?

    • User Avatar
      Steve
      Permalink to comment#

      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:

       function fix_svg() {
          echo '<style type="text/css">
                .attachment-266x266, .thumbnail img { 
                     width: 100% !important; 
                     height: auto !important; 
                }
                </style>';
       }
       add_action('admin_head', 'fix_svg');
      
    • User Avatar
      CFX
      Permalink to comment#

      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 selector img[src$=".svg"]:

      function custom_admin_head() {
        $css = '';
      
        $css = 'td.media-icon img[src$=".svg"] { width: 100% !important; height: auto !important; }';
      
        echo '<style type="text/css">'.$css.'</style>';
      }
      add_action('admin_head', 'custom_admin_head');
      
  5. User Avatar
    Z
    Permalink to comment#

    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?

  6. User Avatar
    John M
    Permalink to comment#

    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!

    • User Avatar
      John M
      Permalink to comment#

      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.

  7. User Avatar
    Chris
    Permalink to comment#

    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…

  8. User Avatar
    ryan
    Permalink to comment#

    How does css-tricks always have an article on exactly what I am trying to do? the best.

  9. User Avatar
    SalamMedia
    Permalink to comment#

    Thank you so much for this!

  10. User Avatar
    Victor Bonilla
    Permalink to comment#

    Yes, it allows me to upload the svg images, but I can’t see them in my front, don’t know why :\

    • User Avatar
      Victor Bonilla
      Permalink to comment#

      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?

    • User Avatar
      Mike Bazil
      Permalink to comment#

      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:

          // we have the actual image size, but might need to further constrain it if content_width is narrower
          list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
      

      with:

          $img_ext = pathinfo($img_url, PATHINFO_EXTENSION);
          if ($img_ext != 'svg') 
          {
              // we have the actual image size, but might need to further constrain it if content_width is narrower
              list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
          }
      

      you still can not see the thumbnail for svg files, but I have not time to fix that.

  11. User Avatar
    Catherine
    Permalink to comment#

    THANKYOU

  12. User Avatar
    mommaroodles
    Permalink to comment#

    2014 and I find this snippet now only – I must be sleeping under a log!!! Thank you so much :)

  13. User Avatar
    Dan
    Permalink to comment#

    How would I resize the svg images?

  14. User Avatar
    Native Imaging
    Permalink to comment#

    Doesn’t work with WP 3.8.1

    • User Avatar
      Chris Coyier
      Permalink to comment#

      I’m on 3.8.1 right this second and it works for me. Any specifics?

  15. User Avatar
    Ulrike
    Permalink to comment#

    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).

  16. User Avatar
    frank
    Permalink to comment#

    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?

  17. User Avatar
    Jason Whittemore
    Permalink to comment#

    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

  18. User Avatar
    Jens Törnell
    Permalink to comment#

    What about security? Why are SVG files blocked in the first place by WordPress? Could this mean danger to the sites?

  19. User Avatar
    telemarker
    Permalink to comment#

    i read all of the comments and this snipped is working well for wordpress 3.8.2

    ##################################################################
    
    enable images in media uploader
    
    ##################################################################
    function cc_mime_types( $mimes ){
        $mimes['svg'] = 'image/svg+xml';
        return $mimes;
    }
    add_filter( 'upload_mimes', 'cc_mime_types' );
    
    ##################################################################
    
    display images on media uploader and feature images
    
    ##################################################################
    
    function fix_svg() {
        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');
    

    for the use of the feature images on the front-end you have to style the post-image via css:

    /* svg on feature images */
    img.wp-post-image { width: 100% !important; height: auto !important; }</code>
    
  20. User Avatar
    telemarker
    Permalink to comment#

    for fallbacks use svgmagic, cool jqueryplugin

  21. User Avatar
    Lucas

    Thanks! Works fine for me.

  22. User Avatar
    Ramses

    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 (:

  23. User Avatar
    rachael knight

    Not working for me, WP 3.8.3.

  24. User Avatar
    Thomas Federico
    Permalink to comment#

    In functions.php, it works like a charm :)

  25. User Avatar
    Kyle Matthews
    Permalink to comment#

    Still working via WordPress 3.9.2 – and thank you! I wound up using this code:

    /*-----------------------------------------------------------------------------------*/
    /*  enable svg images in media uploader
    /*-----------------------------------------------------------------------------------*/
    function cc_mime_types( $mimes ){
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
    }
    add_filter( 'upload_mimes', 'cc_mime_types' );
    
    /*-----------------------------------------------------------------------------------*/
    /*  display svg images on media uploader and feature images
    /*-----------------------------------------------------------------------------------*/
    function custom_admin_head() {
      $css = '';
    
      $css = 'td.media-icon img[src$=".svg"] { width: 100% !important; height: auto !important; }';
    
      echo ''.$css.'';
    }
    add_action('admin_head', 'custom_admin_head');
    
  26. User Avatar
    Kyle Matthews
    Permalink to comment#

    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.

  27. User Avatar
    Nimmi Thomas
    Permalink to comment#

    Work very well. Thanks saved my time.

  28. User Avatar
    Jimmy Smutek
    Permalink to comment#

    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.

  29. User Avatar
    Hero
    Permalink to comment#

    Thanks a LOT …….keep up the good codes come up :) God Bless You :)

  30. User Avatar
    Ross
    Permalink to comment#

    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.

    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');
    
    
    • User Avatar
      Ross
      Permalink to comment#

      Hmmm. that’s odd. I added a before the td and after the closing CSS bracket. Seems like the comment thing filtered that out.

  31. User Avatar
    Martin Defatte
    Permalink to comment#

    The “Featured Image” display did not work for me until I added another ID.

    #postimagediv img[src$=".svg"]

    function fix_svg_thumb_display() {
      echo '
    
        td.media-icon img[src$=".svg"],
        img[src$=".svg"].attachment-post-thumbnail,
        #postimagediv img[src$=".svg"]{ 
          width: 100% !important; 
          height: auto !important; 
        }
    
      ';
    }
    add_action('admin_head', 'fix_svg_thumb_display');
    
    • User Avatar
      telemarker
      Permalink to comment#

      you are right, i found out you can use

      .postbox img[src$=”.svg”]
      too

  32. User Avatar
    Ilia
    Permalink to comment#

    Does not work…

    Why WP save svg as ‘.png’ file?

  33. User Avatar
    Gray Ayer
    Permalink to comment#

    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:

    function fix_svg_thumb_display() {
      echo '<style> td.media-icon img[src$=".svg"], img[src$=".svg"].attachment-post-thumbnail { width: 100% !important; height: auto !important; } </style>';
    }
    add_action('admin_head', 'fix_svg_thumb_display');
    

    NOTE: this only displays in the list view.

  34. User Avatar
    telemarker
    Permalink to comment#

    you got it gray!

    so far this is working well with wordpress 4.0

    ######################################################
    # display images on media uploader (list view only) and feature images 
    ######################################################
    
    function display_svg() {
        echo '';
    }
    add_action('admin_head', 'display_svg');
    
    

    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?

  35. User Avatar
    Andy Galaxy
    Permalink to comment#

    Legend!

  36. User Avatar
    Joseph Rex
    Permalink to comment#

    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

  37. User Avatar
    Christopher Curtin
    Permalink to comment#

    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?

    <# if ( 'svg+xml' === data.subtype ) { #>
       <div class="centered">
          <img src="{{ data.url }}" class="thumbnail" draggable="false" />
       </div>
    <# }
    

    Can someone explain what would be incorrect about doing that? A security risk? Enlighten me!

  38. User Avatar
    wilfred
    Permalink to comment#

    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.!

  39. User Avatar
    Eduard
    Permalink to comment#

    Thanks!! This really helped me a lot :)

  40. User Avatar
    Christian Dion
    Permalink to comment#

    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…

  41. User Avatar
    Lewis Cowles (@LewisCowles1)
    Permalink to comment#

    Solved it!

    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!

    • User Avatar
      Lewis Cowles
      Permalink to comment#

      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.

  42. User Avatar
    Lewis Cowles (@LewisCowles1)
    Permalink to comment#

    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???)

    • User Avatar
      Benbodhi

      @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

    • User Avatar
      Lewis Cowles (@LewisCowles1)

      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…

  43. User Avatar
    Nathan Fazakerly

    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.

    • User Avatar
      Lewis Cowles (@Lewiscowles1)

      Hi Nathan,

      I can still upload using the code from this gist, even in 4.2.2…

      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 ;)

    • User Avatar
      Nathan Fazakerly

      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?

  44. User Avatar
    Lewis Cowles (@Lewiscowles1)

    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!

  45. User Avatar
    Nathan Fazakerly

    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 :)

  46. User Avatar
    telemarker
    Permalink to comment#

    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.

    • User Avatar
      Lewis Cowles (@LewisCowles1)
      Permalink to comment#

      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 ;).

  47. User Avatar
    n3nad
    Permalink to comment#

    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

  48. User Avatar
    imurphy
    Permalink to comment#

    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.

    • User Avatar
      Bobby
      Permalink to comment#

      Thank you, great tip!! I also am having the error with the new WP 4.7.1 update.

  49. User Avatar
    Guenni
    Permalink to comment#

    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

    • User Avatar
      imurphy
      Permalink to comment#

      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

    • User Avatar
      Ben Usher Smith (@benushersmith)
      Permalink to comment#

      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.

      add_filter( 'wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) {
      
          global $wp_version;
          if ( $wp_version !== '4.7.1' ) {
             return $data;
          }
      
          $filetype = wp_check_filetype( $filename, $mimes );
      
          return [
              'ext'             => $filetype['ext'],
              'type'            => $filetype['type'],
              'proper_filename' => $data['proper_filename']
          ];
      
      }, 10, 4 );
      

      It should work with the Safe SVG plugin I suggested below yesterday.

      Whatever you do don’t use the work around suggesting you include…

      define( 'ALLOW_UNFILTERED_UPLOADS', true );
      

      in your wp-configfile. It’s Super insecure!

      PHP file uploads anyone! :-|

    • User Avatar
      Ben Usher Smith (@benushersmith)
      Permalink to comment#

      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 :-)

    • User Avatar
      Lewis Cowles
      Permalink to comment#

      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

      add_filter( 'wp_check_filetype_and_ext', function($data) {
          if(isset($data['ext'])) {
              if($data['ext'] === 'svg') {
                  $data['type'] = 'image/svg+xml';
              }
          }
          return $data;
      } );
      

      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

  50. User Avatar
    Joshua
    Permalink to comment#

    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:

    function bodhi_svgs_disable_real_mime_check( $data, $file, $filename, $mimes ) {
        $wp_filetype = wp_check_filetype( $filename, $mimes );
    
        $ext = $wp_filetype['ext'];
        $type = $wp_filetype['type'];
        $proper_filename = $data['proper_filename'];
    
        return compact( 'ext', 'type', 'proper_filename' );
    }
    add_filter( 'wp_check_filetype_and_ext', 'bodhi_svgs_disable_real_mime_check', 10, 4 );
    

    Full credit goes to the SVG Support Plugin

    • User Avatar
      Beth
      Permalink to comment#

      I noticed this! Thanks your code fixed the update issue for me!

    • User Avatar
      Ed
      Permalink to comment#

      On 4.7.2 XLSX file uploads are also broken. This code fixed it.

    • User Avatar
      anarcode
      Permalink to comment#

      Small optimizations like eliminate a bunch of variables and a function call.

      add_filter('wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) {
          $wp_filetype = wp_check_filetype($filename, $mimes);
          return [
              'ext' => $wp_filetype['ext']
              , 'type' => $wp_filetype['type']
              , 'proper_filename' => $data['proper_filename']
          ];
      }, 10, 4);
      
  51. User Avatar
    Ben Usher Smith (@benushersmith)
    Permalink to comment#

    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.

    • User Avatar
      Lewis Cowles
      Permalink to comment#

      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).

  52. User Avatar
    Praveen
    Permalink to comment#

    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’ );

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag