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

I tried hooking the upload_mimes hook in order to add support for ttf files to be uploaded, however this didn't immediately work (.ttf files were still blocked).

The reason isn't entirely clear to me but I assume Wordpress's calculated MIME type for the file I'm trying to upload and the MIME type I'm adding to the upload_files hook don't match.

Topic fonts uploads Wordpress

Category Web


If you're not in production or i.e. working in development env you can use:

define('ALLOW_UNFILTERED_UPLOADS', true);

in wp-config.php


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' );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.