Support SVG images in WordPress by custom code

Here’s a code snippet that you can use to add support for SVG images in WordPress:

function add_svg_support( $mimes ) {
  $mimes['svg'] = 'image/svg+xml';
  return $mimes;
}
add_filter( 'upload_mimes', 'add_svg_support' );

This code adds the SVG MIME type to the list of allowed file types in WordPress. You can add this code to your theme’s functions.php file or in a custom plugin.

Another thing you can do is to sanitize the SVG file before uploading it to the media library, this way you can prevent any security vulnerabilities.

function sanitize_svg_upload( $file ) {
    $file_ext = strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) );
    if ( $file_ext !== 'svg' ) {
        return $file;
    }
    $file['name'] = sanitize_file_name( $file['name'] );
    $file['name'] = preg_replace( '/[^a-z0-9_\-\.]/i', '', $file['name'] );
    $file['name'] = preg_replace( '/[\s-]+/', '-', $file['name'] );
    $file['name'] = preg_replace( '/^[\s-]/', '', $file['name'] );
    $file['name'] = preg_replace( '/[\s-]$/', '', $file['name'] );
    $file['name'] = str_replace( 'svg-', 'svg.', $file['name'] );
    $file_type = wp_check_filetype( $file['name'], array( 'svg' => 'image/svg+xml' ) );
    $file['type'] = $file_type['type'];
    return $file;
}
add_filter( 'wp_handle_upload_prefilter', 'sanitize_svg_upload' );

Please test these codes in development environment before deploying it to production.

Leave a Reply