2

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 4

3

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');
1
  • 1
    I'd like to testify that this answer works with text/plain whereas the selected answer with application/json doesn't. Jul 24, 2022 at 1:56
2

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');
1
  • Thank you, now I feel stupid that I haven’t recognized that issue 😄
    – luki512
    Aug 18, 2020 at 9:01
1

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');
``
0
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.