How can I allow upload of ttf or otf font files when hooking `upload_mimes` doesn’t work

This is an imperfect solution which forces the way WordPress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

First massage the way WordPress detects/reports TTF file types:

function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {

if ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {
return $data;
}

$wp_file_type = wp_check_filetype( $filename, $mimes );

// Check for the file type you want to enable, e.g. 'svg'.
if ( 'ttf' === $wp_file_type['ext'] ) {
$data['ext'] = 'ttf';
$data['type'] = 'font/ttf';
}

if ( 'otf' === $wp_file_type['ext'] ) {
$data['ext'] = 'otf';
$data['type'] = 'font/otf';
}

return $data;
}
add_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );

Then hook upload_mimes for exactly this extension/mime-type:


function allow_custom_mime_types( $mimes ) {
 
    // New allowed mime types.
    $mimes['ttf'] = 'font/ttf';     

    return $mimes;
}

add_filter( 'upload_mimes', 'allow_custom_mime_types' );