Allow SVG Uploads for Administrators
Lets administrators upload SVG files to the Media Library. Files containing scripts, event handlers or javascript: links are rejected.
Opens WPIDE on
Code
add_filter( 'upload_mimes', function ( $mimes ) {
if ( current_user_can( 'manage_options' ) ) {
$mimes['svg'] = 'image/svg+xml';
}
return $mimes;
} );
add_filter( 'wp_check_filetype_and_ext', function ( $data, $file, $filename, $mimes ) {
if ( ! current_user_can( 'manage_options' ) ) {
return $data;
}
$check = wp_check_filetype( $filename, $mimes );
if ( 'svg' !== $check['ext'] ) {
return $data;
}
$contents = is_readable( $file ) ? (string) file_get_contents( $file, false, null, 0, 2 * MB_IN_BYTES ) : '';
if ( '' === $contents || preg_match( '/<script|\son[a-z]+\s*=|javascript:|<foreignObject/i', $contents ) ) {
return array( 'ext' => false, 'type' => false, 'proper_filename' => false );
}
$data['ext'] = 'svg';
$data['type'] = 'image/svg+xml';
return $data;
}, 10, 4 );
Notes
The check is a basic safety net, not a full SVG sanitizer. Only upload SVG files from sources you trust.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.