Allow upload SVG files to WordPress

How to allow SVG uploads in WordPress

SVG is the format of choice for logos and icons, but WordPress blocks it out of the box. There are two ways to enable it: install a plugin, or add a small filter to your theme or plugin code.

Problem: WordPress blocks SVG uploads by default.

Solution: There are two options: install a plugin or write custom code. WordPress has several plugins for this; Safe SVG and SVG Support are popular choices. If you’d rather handle it in code, read on.

Allow SVG with the upload_mimes filter

add_filter( 'upload_mimes', 'helloadmin_allow_svg' );
function helloadmin_allow_svg( $mimes ) {
    // Only administrators may upload SVG.
    if ( current_user_can( 'manage_options' ) ) {
        $mimes['svg'] = 'image/svg+xml';
    }

    return $mimes;
}

The capability check limits SVG uploads to administrators. That is important, see below. Using the same filter, you can also enable other file types that WordPress blocks by default. To see the full list of currently allowed MIME types, use:

print_r( get_allowed_mime_types() );

Why SVG is blocked: security

An SVG file is an XML document, not a picture made of pixels. It can contain JavaScript, links to external resources and other active content. If someone uploads such a file and a visitor opens it directly, the script runs on your domain: a classic stored XSS. That is why SVG files must be sanitized before upload, meaning that everything except the drawing itself is removed from the file. You can do it with an online tool or a server-side library; a library is more reliable because it works on every upload. The Safe SVG plugin handles both the MIME type and sanitization in one step.

Still “Sorry, this file type is not permitted for security reasons”?

Even with the filter above, some SVG files still fail with this message. WordPress checks the real content of the file, not just the extension, and an SVG without an XML declaration at the top is sometimes not recognised as image/svg+xml. Open the file in any text editor, add this line at the very top and save:

<?xml version="1.0" encoding="utf-8"?>

If that doesn’t help, check that the file is saved as UTF-8 without BOM. Some editors add a byte order mark at the start of the file, which confuses the server-side MIME detection.

Sources:

  1. https://kinsta.com/blog/wordpress-svg/
  2. https://developer.wordpress.org/reference/functions/get_allowed_mime_types/