Last active
October 3, 2023 13:16
-
-
Save kamalahmed/faa48043b7c3f9a63f6c3c8c8d21ec96 to your computer and use it in GitHub Desktop.
Fix the “Sorry, this file type is not permitted for security reasons.” issue on WordPress while uploading an SVG file
This file contains hidden or 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 | |
/** | |
* A workaround for upload validation which relies on a PHP extension (fileinfo) with inconsistent reporting behaviour. | |
* ref: https://core.trac.wordpress.org/ticket/39550 | |
* ref: https://core.trac.wordpress.org/ticket/40175 | |
*/ | |
function prefix_filter_fix_wp_check_filetype_and_ext( $data, $file, $filename, $mimes ) { | |
if ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) { | |
return $data; | |
} | |
$registered_file_types = ['svg' => 'image/svg+xml|application/octet-stream|image/x-svg+xml'];// add other non-supported mime types if needed | |
$filetype = wp_check_filetype( $filename, $mimes ); | |
if ( ! isset( $registered_file_types[ $filetype['ext'] ] ) ) { | |
return $data; | |
} | |
return [ | |
'ext' => $filetype['ext'], | |
'type' => $filetype['type'], | |
'proper_filename' => $data['proper_filename'], | |
]; | |
} | |
/** | |
* Allow files with .svg extension to be uploaded via | |
* the wordpress media uploader | |
* | |
* | |
* @param array $mime_types Existing allowed mime types | |
* @return array | |
*/ | |
function prefix_allow_svg( $mime_types ) { | |
if ( ! in_array( 'svg', $mime_types ) ) { // Check if it hasn't been enabled already | |
// allow SVG file upload | |
$mime_types['svg'] = 'image/svg+xml|application/octet-stream|image/x-svg+xml'; | |
} | |
return $mime_types; | |
} | |
add_filter( 'wp_check_filetype_and_ext', 'prefix_filter_fix_wp_check_filetype_and_ext', 10, 4 ); | |
add_filter( 'upload_mimes', 'prefix_allow_svg' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment