Skip to content

Instantly share code, notes, and snippets.

@AnadarProSvcs
Created January 30, 2024 14:23
Show Gist options
  • Save AnadarProSvcs/ddb7bf81cf60a59b70fe103e9be6651d to your computer and use it in GitHub Desktop.
Save AnadarProSvcs/ddb7bf81cf60a59b70fe103e9be6651d to your computer and use it in GitHub Desktop.
Allow SVG Uploads in WordPress - Controlled by user role
/**
* Enable SVG file uploads for users with specific roles.
*
* @param array $upload_mimes Permitted mime types.
* @return mixed Updated list of mime types.
*/
add_filter(
'upload_mimes',
function ( $upload_mimes ) {
// Restrict SVG upload capability to users with certain roles for security reasons.
// Modify the following condition to extend or restrict SVG upload capabilities.
if ( ! current_user_can( 'administrator' ) ) {
return $upload_mimes;
}
// Adding SVG and SVGZ mime types to the list of allowed mime types.
$upload_mimes['svg'] = 'image/svg+xml';
$upload_mimes['svgz'] = 'image/svg+xml';
return $upload_mimes;
}
);
/**
* Validate SVG file uploads based on mime type.
*
* @param array $wp_check_filetype_and_ext Validation result for the file.
* @param string $file Full path to the file being checked.
* @param string $filename Name of the file, potentially different from $file.
* @param string[] $mimes Known mime types indexed by file extension regex.
* @param string|false $real_mime Actual mime type of the file, or false if undetermined.
* @return array Updated file validation results.
*/
add_filter(
'wp_check_filetype_and_ext',
function ( $wp_check_filetype_and_ext, $file, $filename, $mimes, $real_mime ) {
// Proceed only if the file type is not already determined.
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;
// Exclude non-SVG images from being processed as SVG.
if ( $type && 0 === strpos( $type, 'image/' ) && 'svg' !== $ext ) {
$ext = false;
$type = false;
}
// Compacting the variables for returning.
$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