This WordPress snippet allows administrators to upload SVG files by modifying the site’s allowed MIME types. It includes a security measure that restricts SVG uploads to administrator users only, mitigating potential risks associated with SVG file uploads from other user roles
function snn_allow_svg_upload( $upload_mimes ) {
if ( ! current_user_can( 'administrator' ) ) {
return $upload_mimes;
}
$upload_mimes['svg'] = 'image/svg+xml';
$upload_mimes['svgz'] = 'image/svg+xml';
return $upload_mimes;
}
add_filter( 'upload_mimes', 'snn_allow_svg_upload' );
function snn_svg_mime_check( $wp_check_filetype_and_ext, $file, $filename, $mimes, $real_mime ) {
if ( ! $wp_check_filetype_and_ext['type'] ) {
$check_filetype = wp_check_filetype( $filename, $mimes );
$ext = $check_filetype['ext'];
$type = $check_filetype['type'];
$proper_filename = $filename;
if ( $type && 0 === strpos( $type, 'image/' ) && 'svg' !== $ext ) {
$ext = false;
$type = false;
}
$wp_check_filetype_and_ext = compact( 'ext', 'type', 'proper_filename' );
}
return $wp_check_filetype_and_ext;
}
add_filter( 'wp_check_filetype_and_ext', 'snn_svg_mime_check', 10, 5 );