Last active
January 30, 2024 14:50
-
-
Save knolaust/12f328eca773af73d65acea1c280b36b to your computer and use it in GitHub Desktop.
Allow SVG Files Upload in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Allow SVG uploads for administrator users. | |
* | |
* This function modifies the list of allowed mime types for file uploads in WordPress. | |
* Specifically, it enables SVG and SVGZ file uploads for users with the 'administrator' role. | |
* This can enhance flexibility for site customization while maintaining security. | |
* | |
* Gist Keywords: wordpress, file upload, svg, functions, mime, security | |
* | |
* @param array $upload_mimes The existing array of allowed mime types. | |
* @return array The modified array of mime types. | |
* @author Knol Aust | |
*/ | |
add_filter( | |
'upload_mimes', | |
function ( $upload_mimes ) { | |
if ( ! current_user_can( 'administrator' ) ) { | |
return $upload_mimes; | |
} | |
$upload_mimes['svg'] = 'image/svg+xml'; | |
$upload_mimes['svgz'] = 'image/svg+xml'; | |
return $upload_mimes; | |
} | |
); | |
/** | |
* Add SVG files mime check. | |
* | |
* This function ensures proper handling of SVG file uploads by checking and validating the file type. | |
* It's particularly useful for security, ensuring that only legitimate SVG files are processed and uploaded. | |
* | |
* Categories: #wordpress, #file-upload, #svg, #validation, #security | |
* | |
* @param array $wp_check_filetype_and_ext File type and extension data. | |
* @param string $file Full path to the file. | |
* @param string $filename The name of the file. | |
* @param string[] $mimes Array of mime types keyed by their file extension regex. | |
* @param string|false $real_mime The actual mime type or false if the type cannot be determined. | |
* @return array Modified file type and extension data. | |
* @author Knol Aust | |
*/ | |
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 | |
); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment