Last updated on September 13, 2023

Allow SVG Files Upload

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Enable SVG files to be uploaded to WordPress.

By default, WordPress doesn’t allow uploading SVG files as a security measure. However, if you want to allow SVG files to be uploaded to your website, you can use the following code snippet:

function wpsnippets_allow_svg_files( $mime_types ) {
    $mime_types['svg'] = 'image/svg+xml';
    $mime_types['svgz'] = 'image/svg+xml';
    return $mime_types;
}

add_filter( 'upload_mimes', 'wpsnippets_allow_svg_files');

This code adds the SVG and SVGZ file types to the list of allowed MIME types for file uploads in WordPress. Once you have added this code snippet, you should be able to upload SVG files just like any other image file.

Only allow SVG files for specific users

Should you want to only allow SVG files to be uploaded for specific users, you can for example check for a users capabilities as follows:

function wpsnippets_allow_svg_files( $mime_types ) {

    // Return original value if user doesn't have a required capability
    if( ! current_user_can( 'manage_options' ) ) {
        return $mime_types;
    }

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

add_filter( 'upload_mimes', 'wpsnippets_allow_svg_files');

Another way to check for a specific user is to only allow a user with a specific user ID to upload SVG files:

function wpsnippets_allow_svg_files( $mime_types ) {

    // Return original value if user ID is not 123
    if( 123 !== get_current_user_id() ) {
        return $mime_types;
    }

    // Allow SVG for the user with ID 123
    $mime_types['svg'] = 'image/svg+xml';
    $mime_types['svgz'] = 'image/svg+xml';
    return $mime_types;
}

add_filter( 'upload_mimes', 'wpsnippets_allow_svg_files');

Last updated on September 13, 2023. Originally posted on April 30, 2023.

Leave a Reply

Your email address will not be published. Required fields are marked *