Home / Admin / Enable JSON and SVG uploads for administrator users only
Duplicate Snippet

Embed Snippet on Your Site

Enable JSON and SVG uploads for administrator users only

Code Preview
php
<?php
/**
 * Enable JSON and SVG uploads for administrator users only.
 */
add_filter( 'upload_mimes', function ( $upload_mimes ) {
    // Only allow for administrators
    if ( ! current_user_can( 'administrator' ) ) {
        return $upload_mimes;
    }
    // Add SVG support
    $upload_mimes['svg']  = 'image/svg+xml';
    $upload_mimes['svgz'] = 'image/svg+xml';
    // Add JSON support
    $upload_mimes['json'] = 'text/plain';
    return $upload_mimes;
} );
/**
 * Ensure WordPress properly validates SVG and JSON MIME types.
 */
add_filter(
    'wp_check_filetype_and_ext',
    function ( $wp_check_filetype_and_ext, $file, $filename, $mimes, $real_mime ) {
        if ( ! $wp_check_filetype_and_ext['type'] ) {
            $check = wp_check_filetype( $filename, $mimes );
            $ext   = $check['ext'];
            $type  = $check['type'];
            $proper_filename = $filename;
            // Allow SVG, JSON, and image types
            if ( $type && (
                0 === strpos( $type, 'image/' ) ||
                in_array( $type, [ 'image/svg+xml', 'application/json', 'text/plain' ], true )
            ) ) {
                // Normalize JSON MIME type
                if ( 'json' === $ext && ! in_array( $type, [ 'application/json', 'text/plain' ], true ) ) {
                    $type = 'application/json';
                }
                // Normalize SVG MIME type
                if ( in_array( $ext, [ 'svg', 'svgz' ], true ) && 'image/svg+xml' !== $type ) {
                    $type = 'image/svg+xml';
                }
                return compact( 'ext', 'type', 'proper_filename' );
            }
            return $wp_check_filetype_and_ext;
        }
        return $wp_check_filetype_and_ext;
    },
    10,
    5
);
/**
 * Optional: Sanitize SVG uploads using Safe SVG plugin if available.
 */
add_filter( 'wp_handle_upload_prefilter', function ( $file ) {
    if (
        current_user_can( 'administrator' ) &&
        isset( $file['type'] ) &&
        'image/svg+xml' === $file['type']
    ) {
        // Optional: sanitize SVG using Safe SVG plugin
        if ( function_exists( 'safe_svg_sanitize' ) ) {
            $file['tmp_name'] = safe_svg_sanitize( $file['tmp_name'] );
        }
    }
    return $file;
} );

Comments

Add a Comment