For security purposes, WordPress only allows images, documents, video, and audio files to upload as per the documenation. But thanks to filters and hooks to extend or create new functionality.

In this tutorial, we are going to use two filters to allow the SVG file to upload i.e. upload_mimes and wp_check_filetype_and_ext.

The upload_mimes filter helps to allow users to the newly added file type. In our example, we are going to allow SVG files to upload. And the wp_check_filetype_and_ext filter helps to add the validation rules for the uploaded file.

Enable SVG uploads

Let’s jump to the first part to allow users to upload the SVG file by adding the file extension and type. For SVG we will use two extensions i.e. .svg and .svgz. Where .svg is the normal file extension for the SVG file and .svgz is for the gzip-compressed SVG file.

Make sure to add the below code at the bottom of the functions.php file. We are allowing this SVG file upload only to the users who have administrator access.

add_filter( 'upload_mimes', 'wrg30_upload_mimes' );
function wrg30_upload_mimes( $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;
}

Validation Rules for SVG upload

The next step is to implement the file validation rules. The uploaded file type should have image/ string and should match the SVG file extension.

add_filter( 'wp_check_filetype_and_ext', 'wrg30_check_filetype_and_ext', 10, 5 );

function wrg30_check_filetype_and_ext( $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;
}

Need Help?

If you find it difficult to implement or don’t know what to do where? You can contact us to do this.

We believe this article will help you to allow SVG file upload. And if you enjoyed this article, then please follow us for more interesting and helpful tutorials. You can follow us on Facebook and Twitter.

Pin It on Pinterest

Shares