← All Articles A Product of Kinsa Creative

Allow SVG File Uploads via the WordPress Media Uploader

WordPress sees SVG files as a security risk because they are XML based. To safely allow SVG uploads and update the WP Admin to display them correctly, add the following three functions to the theme's functions.php file.

This code hooks into the upload_mimes hook to add the image/svg+xml mime type and uses the wp_check_filetype_and_ext hook to validate that the uploaded file contents match the mime type indicated.''

According to CSS Tricks, the CSS fixes the output of the SVG images in the WP Admin Media Grid.

// allow SVG file uploads
// from https://wpengine.co.uk/resources/enable-svg-wordpress/

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

function cc_mime_types( $mimes ) {
    $mimes['svg'] = 'image/svg+xml';

    return $mimes;
}

add_filter( 'upload_mimes', 'cc_mime_types' );

function fix_svg() {
    echo '';
}

add_action( 'admin_head', 'fix_svg' );

Feedback?

Email us at enquiries@kinsa.cc.