Do you want to allow SVG uploads on your WordPress website?
By default, WordPress allows you to upload audio, video, and image file formats. WordPress doesn’t offer SVG uploads due to security reasons and you may encounter an error while uploading the SVG file to the WordPress media library.
Allow SVG Uploads For All Users
If you want to enable the SVG uploads in WordPress, you can use the below code.
/**
* Add Mime Types
*/
function maverick_svgs_upload_mimes($mimes = array())
{
if (current_user_can('administrator')) {
// allow SVG file upload
$mimes['svg'] = 'image/svg+xml';
$mimes['svgz'] = 'image/svg+xml';
return $mimes;
} else {
return $mimes;
}
}
add_filter('upload_mimes', 'maverick_svgs_upload_mimes', 99);
/**
* Check Mime Types
*/
function maverick_svgs_upload_check($checked, $file, $filename, $mimes)
{
if (!$checked['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/') && $ext !== 'svg') {
$ext = $type = false;
}
$checked = compact('ext', 'type', 'proper_filename');
}
return $checked;
}
add_filter('wp_check_filetype_and_ext', 'maverick_svgs_upload_check', 10, 4);
/**
* Mime Check fix for WP 4.7.1 / 4.7.2
*
* Fixes uploads for these 2 version of WordPress.
* Issue was fixed in 4.7.3 core.
*/
function maverick_svgs_allow_svg_upload($data, $file, $filename, $mimes)
{
global $wp_version;
if ($wp_version !== '4.7.1' || $wp_version !== '4.7.2') {
return $data;
}
$filetype = wp_check_filetype($filename, $mimes);
return [
'ext' => $filetype['ext'],
'type' => $filetype['type'],
'proper_filename' => $data['proper_filename']
];
}
add_filter('wp_check_filetype_and_ext', 'maverick_svgs_allow_svg_upload', 10, 4);
Allow SVG Uploads Only For Administrators
Since uploading the SVG files can put your site at risk, you can restrict SVG file upload to Site Administrators. You can use the below code to allow SVG file uploads only by administrators.
//Enable SVG upload Only by Administrators
function maverick_enable_svg_upload($mimes)
{
//Only allow SVG upload by admins
if (!current_user_can('administrator')) {
return $mimes;
}
$mimes['svg'] = 'image/svg+xml';
$mimes['svgz'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimesv', 'maerick_enable_svg_upload');