Allow .json upload file in WordPress

Viewed 4451

I want to upload .json files in my media library in WordPress. The reason for this is that I'm using lottie animations and the output is an animated .svg file. I just want to retrieve the file url from the backend to use it in the frontend. Unfortunately .json doesn't work to import even with the usage of the following code:

function cc_mime_types($mimes) {
    $mime_types = array(
        'svg'     => 'image/svg+xml',
        'json'     => 'application/json',
    );
    return $mimes;
   }
add_filter('upload_mimes', 'cc_mime_types');

define( 'ALLOW_UNFILTERED_UPLOADS', true );

Does anyone knows a solution for this kind of problem?

Best regards!

4 Answers

Since PHP determines the mime type of json files to be text/plain (see here for more) the correct solution is:

function my_mime_types($mimes) {
    $mimes['json'] = 'text/plain';
    return $mimes;
}
add_filter('upload_mimes', 'my_mime_types');

In your original code, you're declaring the new mime types in $mime_types but don't do anything with it, instead you're returning the original unchanged $mimes.


As for your working solution, you could use only one function as follows:

function cc_mime_types($mimes) {
    $mimes['json'] = 'application/json';
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');

I just added two different functions instead of an array and for some reason it worked.

function json_mime_types($mimes) {
    $mimes['json'] = 'application/json';
    return $mimes;
   }
add_filter('upload_mimes', 'json_mime_types');

function cc_mime_types($mimes) {
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
   }
add_filter('upload_mimes', 'cc_mime_types');
``

If this helps anyone, neither the ALLOW_UNFILTERED_UPLOADS constant or the upload_mimes filter will work on their own if you are using WordPress Multisite where the list of allowed file types for your sub-sites needs to be declared first within the ‘Network Admin’ -> ‘Settings’ page within WordPress. Obviously your WordPress user needs sufficient privs in order to be able to see this settings page.

In my experience, once you've added json to this list, the upload_mimes filter will work as expected.

Related