admin管理员组

文章数量:1287597

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.

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.

Share Improve this question asked Sep 30, 2021 at 13:09 mozbozmozboz 2,6281 gold badge12 silver badges23 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 3

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

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

本文标签: How can I allow upload of ttf or otf font files when hooking uploadmimes doesn39t work