admin管理员组

文章数量:1426121

Trying to add certain allowed MIME types to the upload filter - currently my custom function looks like this:

// allow SVG and video mime types for upload
function cc_mime_types( $mimes ){
    $mimes['svg']  = 'image/svg+xml';
    $mimes['webm'] = 'video/webm';
    $mimes['mp4']  = ['video/mp4','video/mpeg'];
    $mimes['ogg']  = 'video/ogg';
    $mimes['ogv']  = 'video/ogg';
    return $mimes;
}
add_filter( 'upload_mimes', 'cc_mime_types' );

Uploading videos with ogg/ogv format seems to work well, but MP4 is failing. It seems like an array of different MIME types is not the solution. How should I add this?

Trying to add certain allowed MIME types to the upload filter - currently my custom function looks like this:

// allow SVG and video mime types for upload
function cc_mime_types( $mimes ){
    $mimes['svg']  = 'image/svg+xml';
    $mimes['webm'] = 'video/webm';
    $mimes['mp4']  = ['video/mp4','video/mpeg'];
    $mimes['ogg']  = 'video/ogg';
    $mimes['ogv']  = 'video/ogg';
    return $mimes;
}
add_filter( 'upload_mimes', 'cc_mime_types' );

Uploading videos with ogg/ogv format seems to work well, but MP4 is failing. It seems like an array of different MIME types is not the solution. How should I add this?

Share Improve this question asked May 29, 2019 at 12:33 BlackbamBlackbam 57511 silver badges28 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

This filter only accepts strings for mime types. It also already has support for webm, mp4, mpeg, ogv, and ogg.

I think you can remove everything except the line for SVGs.

A word of warning, WordPress doesn't support SVG upload by default because it's a security concern. Be careful about enabling this. At the least, use something like the Safe SVG plugin to help mitigate the risk.

@MikeNGarret's answer pointed me to the interesting function wp_get_mime_types(). Within this function you can look up how to correctly add MIME types to the upload_mimes filter (https://core.trac.wordpress/browser/tags/5.1.1/src/wp-includes/functions.php#L2707).

The correct answer therefore is:

// allow SVG and video mime types for upload
function cc_mime_types( $mimes ){
    $mimes['svg']      = 'image/svg+xml';
    $mimes['webm']     = 'video/webm';
    $mimes['mp4|m4v']  = 'video/mp4';
    $mimes['mpeg|mpg|mpe']  = 'video/mpeg';
    $mimes['ogv']      = 'video/ogg';
    return $mimes;
}
add_filter( 'upload_mimes', 'cc_mime_types' );

For registering an unknown MIME type you should therefore use the mime_types filter, for the upload (independently) you have to add it to the list of allowed upload mimes.

本文标签: