Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Populate file info for JSON files so that they can be uploaded to WordPress.
<?php
/**
* Populate file info for JSON files.
*
* @see https://core.trac.wordpress.org/ticket/45633
*
* @param array $info The existing file data array.
* @param string $file Full path to the file.
* @param string $filename The name of the file.
* @param array $mimes Key is the file extension with value as the mime type.
* @param string|bool $real_mime The actual mime type or false if the type cannot be determined.
* @return array $info The modified file data array.
*/
function my_add_json_mime_types( $info, $file, $filename, $mimes, $real_mime ) {
// Get filetype data.
$wp_filetype = wp_check_filetype( $filename, $mimes );
$ext = $wp_filetype['ext'];
$type = $wp_filetype['type'];
// Skip if not JSON.
if ( $ext !== 'json' ) {
return $info;
}
// Use finfo_file if available to validate non-image files.
if ( empty( $real_mime ) AND function_exists( 'finfo_file' ) ) {
$finfo = finfo_open( FILEINFO_MIME_TYPE );
$real_mime = finfo_file( $finfo, $file );
finfo_close( $finfo );
}
// If the extension matches an alternate mime type, let's use it.
if ( in_array( $real_mime, ['application/json', 'text/plain', 'text/html'] ) ) {
$info['ext'] = $ext;
$info['type'] = $type;
}
// --<
return $info;
}
// Add filter for the above.
add_filter( 'wp_check_filetype_and_ext', 'my_add_json_mime_types', 10, 5 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment