By default, WordPress will not allow you to upload SVG files for security reasons. When the popularity of the SVGs is increasing day by day due to their lightweight and customization abilities compared to the standard image formats, you might also want to start using them on your WordPress installation. You can add SVG upload support using the following code.
Keep in mind that enabling SVG is a security risk, especially if you allow your users to upload them. SVGs can contain bad code which could be harmful. So, it is a good idea to limit the feature only for the admins. The default code provided below restricts the SVG upload to the admins. Do not change it unless you know what you are doing.
Usage
- To implement images that will not lose its quality on different screen sizes.
- To reduce the size of the images considerably by utilizing the small size of the SVGs.
- For websites that use a lot of images repeatedly such as icons, parts of the design, etc.
Code
// Enable the ability to upload SVG files to WordPress
function wpt_enable_svg_upload( $mimes ) {
// Only allow SVG upload to the admins
if ( !current_user_can( 'administrator' ) ) {
return $mimes;
}
$mimes['svg'] = 'image/svg+xml';
$mimes['svgz'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimes', 'wpt_enable_svg_upload');
Explanation
- A comment explaining the code block.
- Creating our function
wpt_enable_svg_upload
by passing an argument$mimes
which will later pass to the default$mimes
set by WordPress. - Another comment implying the user role that can upload the modified mime types.
- Checking the capability of the user is
administrator
. If the user is not an admin, stops the execution of the code. - Returning the
$mimes
without modifying it. So that, anyone other than admins will receive the default mime types. - Closing the
if
statement to check the capability of the user. - Adding
svg
to the WordPress mime types. - Adding
svgz
(a compressed version of SVG) to the mime types. - Returning the
$mimes
to pass to theupload_mimes
function. - Closing our
wpt_enable_svg_upload
funtion. - Adding a filter to the built-in
upload_mimes
function with our newly created function.