Allowing SVG uploads in media uploader without plug-in

I have previously managed to utilise this block of code within my functions.php file to enable and create thumbnails for SVGs that are uploaded to my site:

// ALLOW SVG
    function add_file_types_to_uploads($file_types){
        $new_filetypes = array();
        $new_filetypes['svg'] = 'image/svg+xml';
        $file_types = array_merge($file_types, $new_filetypes );
        return $file_types;
    }
    add_action('upload_mimes', 'add_file_types_to_uploads');

    function common_svg_media_thumbnails($response, $attachment, $meta){
        if($response['type'] === 'image' && $response['subtype'] === 'svg+xml' && class_exists('SimpleXMLElement'))
        {
            try {
                $path = get_attached_file($attachment->ID);
                if(@file_exists($path))
                {
                    $svg = new SimpleXMLElement(@file_get_contents($path));
                    $src = $response['url'];
                    $width = (int) $svg['width'];
                    $height = (int) $svg['height'];

                    //media gallery
                    $response['image'] = compact( 'src', 'width', 'height' );
                    $response['thumb'] = compact( 'src', 'width', 'height' );

                    //media single
                    $response['sizes']['full'] = array(
                        'height'        => $height,
                        'width'         => $width,
                        'url'           => $src,
                        'orientation'   => $height > $width ? 'portrait' : 'landscape'
                    );
                }
            }
            catch(Exception $e){}
        }

        return $response;
    }
    add_filter('wp_prepare_attachment_for_js', 'common_svg_media_thumbnails', 10, 3);
// END ALLOW SVG

I am now trying to copy this code over to a new site but I still receive the error:

"logo.svg” has failed to upload.
Sorry, this file type is not permitted for security reasons.

This site is located within a subdirectory of a non-WordPress website, like:

www.example.co.uk/SITE_DIRECTORY/wp-content/themes/THEME_NAME/functions.php

Am I missing a step to get this working?

~ Please do not reference plug-ins.

~ Please help me get this code snippet that has been previously proven to work on a different site; working on this new site.

Thanks, Jason.

1 Answer
1

function cc_mime_types($mimes) {
  $mimes['svg'] = 'image/svg+xml'; 
  return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types'); 

add in functions.php in your active theme

define('ALLOW_UNFILTERED_UPLOADS', true); 

add in wp-config.php

Leave a Comment