Allow SVG Files Upload in WordPress

01/30/2024
Back to Gists
<?php
/**
 * Allow SVG uploads for administrator users.
 *
 * This function modifies the list of allowed mime types for file uploads in WordPress.
 * Specifically, it enables SVG and SVGZ file uploads for users with the 'administrator' role.
 * This can enhance flexibility for site customization while maintaining security.
 *
 * Gist Keywords: wordpress, file upload, svg, functions, mime, security
 *
 * @param array $upload_mimes The existing array of allowed mime types.
 * @return array The modified array of mime types.
 * @author Knol Aust
 */
add_filter(
    'upload_mimes',
    function ( $upload_mimes ) {
        if ( ! current_user_can( 'administrator' ) ) {
            return $upload_mimes;
        }

        $upload_mimes['svg']  = 'image/svg+xml';
        $upload_mimes['svgz'] = 'image/svg+xml';
        return $upload_mimes;
    }
);

/**
 * Add SVG files mime check.
 *
 * This function ensures proper handling of SVG file uploads by checking and validating the file type.
 * It's particularly useful for security, ensuring that only legitimate SVG files are processed and uploaded.
 *
 * Categories: #wordpress, #file-upload, #svg, #validation, #security
 *
 * @param array        $wp_check_filetype_and_ext File type and extension data.
 * @param string       $file Full path to the file.
 * @param string       $filename The name of the file.
 * @param string[]     $mimes Array of mime types keyed by their file extension regex.
 * @param string|false $real_mime The actual mime type or false if the type cannot be determined.
 * @return array Modified file type and extension data.
 * @author Knol Aust
 */
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_filetype  = wp_check_filetype( $filename, $mimes );
            $ext             = $check_filetype['ext'];
            $type            = $check_filetype['type'];
            $proper_filename = $filename;

            if ( $type && 0 === strpos( $type, 'image/' ) && 'svg' !== $ext ) {
                $ext  = false;
                $type = false;
            }

            $wp_check_filetype_and_ext = compact( 'ext', 'type', 'proper_filename' );
        }

        return $wp_check_filetype_and_ext;
    },
    10,
    5
);
?>