Enable SVG File Uploads in WordPress

By default, WordPress doesn’t support uploading and handling of SVG (Scalable Vector Graphics) files. This code makes sure that SVG files can be uploaded, processed, and displayed properly in the WordPress media library.

function ts_enable_SVG( $mimes ) {
    if ( current_user_can( 'manage_options' ) ) {
        $mimes['svg']  = 'image/svg+xml';
    }

    return $mimes;
}
add_filter( 'upload_mimes', 'ts_enable_SVG' );


function ts_enable_SVG_upload( $types, $file, $filename, $mimes ){
    if( substr( $filename, -4 ) == '.svg' ){
        $types['ext'] = 'svg';
        $types['type'] = 'image/svg+xml';
    }

    return $types;
}

add_filter( 'wp_check_filetype_and_ext', 'ts_enable_SVG_upload', 10, 4 );


function ts_enable_SVG_upload_idc( $response ) {
    if ( $response['mime'] === 'image/svg+xml' ) {
        $response['image'] = [
            'src' => $response['url'],
        ];
    }
    return $response;
}
add_filter( 'wp_prepare_attachment_for_js', 'ts_enable_SVG_upload_idc' );