Home / Admin / SVG upload for WP Admin only
Duplicate Snippet

Embed Snippet on Your Site

SVG upload for WP Admin only

SVGs can be a security risk. Reasons are several. Site Admins may want to screen SVGs themselves before uploading.
This ensure that only site admin for wordpress sites are can upload SVGs.

Code Preview
php
<?php
/**
 * Enable SVG uploads for Administrators only
 */
function enable_svg_uploads_for_admins($mime_types) {
    if (current_user_can('manage_options')) {
        $mime_types['svg'] = 'image/svg+xml';
        $mime_types['svgz'] = 'image/svg+xml';
    }
    return $mime_types;
}
add_filter('upload_mimes', 'enable_svg_uploads_for_admins');
/**
 * Bypass secondary file-type check for SVG uploads by admins
 */
function fix_svg_filetype_check($data, $file, $filename, $mimes) {
    if (current_user_can('manage_options')) {
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if (strtolower($ext) === 'svg' || strtolower($ext) === 'svgz') {
            $data['ext'] = $ext;
            $data['type'] = 'image/svg+xml';
            $data['proper_filename'] = $filename;
        }
    }
    return $data;
}
add_filter('wp_check_filetype_and_ext', 'fix_svg_filetype_check', 10, 4);
/**
 * Fix SVG display in the media library
 */
function fix_svg_media_display($response, $attachment, $meta) {
    if (current_user_can('manage_options') && $response['mime'] === 'image/svg+xml') {
        $response['image'] = array(
            'src'    => $response['url'],
            'width'  => 800,
            'height' => 600,
        );
        $response['thumb'] = $response['icon'];
    }
    return $response;
}
add_filter('wp_prepare_attachment_for_js', 'fix_svg_media_display', 10, 3);

Comments

Add a Comment