Allow SVG uploads in WordPress without a plugin
Let administrators upload SVG files with a short Snipfire snippet. Unlike Safe SVG, it doesn't clean the files, so read what that means before you switch it on.
What Safe SVG does
Safe SVG allows SVG uploads and cleans each file to remove anything harmful, with previews in the media library. The plugin on WordPress.org
What the snippet does the same
- SVG files can be uploaded to the media library.
- WordPress is told the file really is an SVG, so uploads aren't refused when the server reports it as plain text.
What's different
- The plugin sanitises every SVG on upload. The snippet doesn't clean the file at all. An SVG can contain scripts, so only upload files you made or trust.
- The snippet lets administrators upload SVGs and nobody else (on multisite, only super admins). The plugin lets you choose which roles can upload.
- The plugin shows SVG previews in the media library and can optimise files with SVGO. The snippet does neither.
When to keep the plugin Keep the plugin if anyone other than you uploads SVGs, or if the files come from sources you don't control.
The snippet: Let administrators upload SVG images
Administrators can upload SVG files to the media library. Other users can’t, because an SVG file can contain scripts.
<?php
// Only users who may post unfiltered HTML (administrators). Upload only SVG
// files you made or trust.
add_filter(
'upload_mimes',
static function ( $mimes ) {
if ( current_user_can( 'unfiltered_html' ) ) {
$mimes['svg'] = 'image/svg+xml';
}
return $mimes;
}
);
// PHP may report an SVG as plain text; tell WordPress what it really is.
add_filter(
'wp_check_filetype_and_ext',
static function ( $data, $file, $filename ) {
if ( ! current_user_can( 'unfiltered_html' ) || 'svg' !== strtolower( pathinfo( (string) $filename, PATHINFO_EXTENSION ) ) ) {
return $data;
}
$start = is_readable( $file ) ? (string) file_get_contents( $file, false, null, 0, 4096 ) : '';
if ( false !== stripos( $start, '<svg' ) ) {
$data['ext'] = 'svg';
$data['type'] = 'image/svg+xml';
}
return $data;
},
10,
3
);
Notes, where it runs and what it was tested with
Switching from the plugin
- Install the snippet in Snipfire (it arrives switched off).
- Deactivate Safe SVG.
- Switch the snippet on. Snipfire checks the code and test-loads your site first.
- Check the page it affects, then delete the plugin.