phpwordpressmime-typeswordpress-hook

Adding MIME type via functions.php not working (although it works via plugin)


So far I have been using a plugin to add the .csl mime type to my WordPress website. But I've been learning more about child themes and since I already have that, why not get rid of a plugin that does just one job. The following is how it's set up in WP Mime Types Admin and it's been working just fine like that: Working setup within WP Mime Types Admin

The following is what I've tried to add to my functions.php (child theme), but when testing it tells me I'm not allowed to upload it:

    // 04082024 - Add .csl as mime type for upload
function custom_upload_mimes ( $existing_mimes ) {
    $existing_mimes['csl'] = 'application/vnd.citationstyles.style+xml';
 
    return $existing_mimes;
}
 
add_filter('upload_mimes', 'custom_upload_mimes');

Solution

  • The custom filter is alright.

    In addition to that, you must add the mimetype in Upload file types for your site in Network Admin settings.

    This is because the check_upload_mimes function filters out mimetypes not listed in the Network Admin Settings or falls back to 'jpg jpeg png gif'.

    Also, WP disallows uploads if the detected mime-type for other unhandled filetypes are do not match that detected by the fileinfo extension.

    To confirm what the detected mimetype is for your .csl files, you can run in terminal

     file --mime-type bmj.csl
    

    This returns text/xml and not application/vnd.citationstyles.style+xml

    In your child theme functions.php script, you can apply a filter that sets the mime type to same real mime type detected by the fileinfo extension.

    if ( ! function_exists( 'custom_upload_mimes' ) ) :
    function custom_upload_mimes ( $existing_mimes ) {
        $existing_mimes['csl'] = 'text/xml';
        return $existing_mimes;
    }
    endif;
    
    add_filter('upload_mimes', 'custom_upload_mimes');
    

    Another alternative is to update the mimetype database on the server so that fileinfo extension returns application/vnd.citationstyles.style+xml as the mimetype for files with .csl extension.