Embed Snippet on Your Site
How to Allow Upload SVG Files in WordPress Media Library Code | Function.php
This code is a set of WordPress filters designed to enable the upload of SVG (Scalable Vector Graphics) files to the WordPress Media Library. SVG is a widely used vector image format that can be scalable without losing quality.
Here's a breakdown of the code:
1. **Filter to Allow SVG Uploads in Media Library:**
```php
add_filter(
'upload_mimes',
function ( $upload_mimes ) {
// By default, only administrator users are allowed to add SVGs.
// To enable more user types edit or comment the lines below but beware of
// the security risks if you allow any user to upload SVG files.
if ( ! current_user_can( 'administrator' ) ) {
return $upload_mimes;
}
$upload_mimes['svg'] = 'image/svg+xml';
$upload_mimes['svgz'] = 'image/svg+xml';
return $upload_mimes;
}
);
```
This filter hooks into the `upload_mimes` hook, which controls the allowed mime types for file uploads. It adds SVG and SVGZ (compressed SVG) mime types to the list, but only for administrator users. Other user types are excluded for security reasons.
2. **Filter to Add SVG Files Mime Check:**
```php
add_filter(
'wp_check_filetype_and_ext',
function ( $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;
},
10,
5
);
```
This filter hooks into the `wp_check_filetype_and_ext` hook, which is responsible for checking the file type and extension. It specifically handles SVG files. If the file type is not determined (e.g., due to an SVG), it checks the actual file type using `wp_check_filetype`. If the file is an image and not an SVG, it sets the extension and type to false, effectively preventing non-SVG images from being treated as SVG.
In summary, this code allows administrators to upload SVG files to the WordPress Media Library by adding the SVG mime types and performing additional checks to ensure that non-SVG images are not misidentified. Note that enabling SVG uploads for non-administrator users should be done with caution due to potential security risks associated with SVG files.
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
Comments