Published on

How to add a new mime type to WordPress

Authors

I’ve just started using HTML5 video on my website but when I tried to upload a .webm file to WordPress' Media Manager, it presented me with an error.

myvideo.webm has failed to upload due to an error. Sorry, this file type is not permitted for security reasons.

It turns out that WordPress doesn't have .webm as part of it's allowed mime types by default, so we need to add it ourselves.

A quick search on the WordPress core files leads us to the wp_get_mime_types() function in wp-includes/functions.php. Inside this function, WordPress provides us with a filter called mime_types, perfect.

Now that we have a suitable filter, we just need to hook onto it and add our new mime type to the existing mime type array. I’ve added webm in this example, but if you needed to add another mime type, you would simply replace the values with your own. Add the following to your functions.php:

function my_theme_custom_upload_mimes( $existing_mimes ) {
// Add webm to the list of mime types.
$existing_mimes['webm'] = 'video/webm';
// Return the array back to the function with our added mime type.
return $existing_mimes;
}
add_filter( 'mime_types', 'my_theme_custom_upload_mimes' );

Note: Many tutorials on this subject suggest using the upload_mimes filter, but if you’re not careful, you’ll actually replace the entire mime type array, rather than adding to it. This means you won’t be able to upload any file type, but the one you added! not exactly what we want.

If you want to double-check everything went okay, simply dump the contents of the wp_get_mime_types() function directly to your page using a WordPress action hook like template_redirect:

function my_theme_output_upload_mimes() {
var_dump( wp_get_mime_types() );
}
add_action( 'template_redirect', 'my_theme_output_upload_mimes' );

Refresh your website and you’ll see the mime type array (which is really long) with the new mime type added.

And of course to really test that everything worked as expected, upload your file to the media manager which should now upload perfectly.