Allow SVG uploads for administrators
- WordPress
WordPress blocks SVG uploads by default because SVG files can contain embedded JavaScript. While this is a valid security concern for multi-author sites, it’s overly restrictive for single-admin sites where the owner needs to upload logos, icons, and illustrations.
<?php
/**
* Allow SVG Uploads
*
* WordPress blocks SVG uploads by default because SVGs can contain
* embedded JavaScript. This snippet allows SVG uploads for administrators
* only and sanitizes the file by checking for a valid SVG namespace.
* For production use, consider a dedicated SVG sanitization library
* like enshrined/svg-sanitize for deeper protection.
*
* Usage: Add to functions.php.
*
* @category wordpress
* @language php
*
* @author Adame Dahmani https://adame.io
* @support Support my family project: https://adame.io/fundraiser
*/
add_filter( 'upload_mimes', function ( $mimes ) {
if ( current_user_can( 'manage_options' ) ) {
$mimes['svg'] = 'image/svg+xml';
$mimes['svgz'] = 'image/svg+xml';
}
return $mimes;
} );
add_filter( 'wp_check_filetype_and_ext', function ( $data, $file, $filename, $mimes ) {
$ext = pathinfo( $filename, PATHINFO_EXTENSION );
if ( $ext === 'svg' ) {
$data['type'] = 'image/svg+xml';
$data['ext'] = 'svg';
}
return $data;
}, 10, 4 );This allows SVG uploads for administrators only. For production sites with multiple untrusted authors, consider adding the enshrined/svg-sanitize library for deeper sanitization that strips embedded scripts and event handlers.