Skip to content

Enabling SVG uploads in WordPress without opening a hole

If WordPress keeps refusing your SVG logos and icons, you can allow them safely once you understand why it blocks them. You will see the real risk, three safe ways to enable SVG, and how to check the SVG files already in your media library.

If WordPress keeps refusing your SVG logos or icons, this article shows you how to allow SVG uploads without putting your site at risk. WordPress blocks SVG on purpose. An SVG file is a text document written in XML (a markup format similar to HTML) that the browser reads and acts on, and it is served from your own domain. So a <script> element, an onload attribute or a <foreignObject> block hidden inside an uploaded SVG can run code in the browser of whoever opens it. This is called stored cross-site scripting (XSS), because the attack is saved on your site and fires later. The first person to open the file is usually a logged-in administrator browsing the media library, so the code runs with their access. You have three safe choices, and a quick snippet pasted into functions.php is rarely one of them. You can clean, or sanitize, every SVG at upload time with a maintained plugin. You can allow the SVG file type for administrators only and sanitize. Or you can keep SVGs out of the media library and ship them with your theme. All three are covered below. So are the small annoyances that show up once SVG works, such as missing thumbnails, oversized previews and MIME type mismatches. The MIME type is the label that tells WordPress and the browser what kind of file it is.

What you’ll accomplish

  • Understand exactly why WordPress blocks SVG, in terms of what the browser does with the file rather than vague “security reasons”.
  • Pick one of three approaches deliberately, based on who holds upload_files on your site.
  • Enable sanitized SVG uploads with a maintained plugin, and confirm the sanitizer actually stripped a payload you planted.
  • Fix the two cosmetic problems everyone hits next: blank thumbnails in the grid, and previews that fill the whole column.
  • Audit the SVGs already sitting in wp-content/uploads/ with a single command.

Prerequisites

  • WordPress 6.0 or newer, PHP 8.0 or newer. The upload_mimes filter and the wp_check_filetype_and_ext behaviour described here have been stable for many releases.
  • Administrator access to the site, plus either WP-CLI over SSH or SFTP access to the uploads directory for the audit step.
  • A staging copy. Do not test payload files on production, even inert ones.
  • The ability to edit a site-specific plugin or a child theme’s functions.php. Never edit a parent theme directly — an update erases it.
  • If you run behind a CDN or a reverse proxy, access to whatever sets response headers, since part of the mitigation lives there.

How it works

Three separate mechanisms decide whether an SVG upload succeeds, and none of them inspects the file’s contents by default.

Side-by-side SVG upload paths with and without a sanitizer, showing where an unsanitized payload executes in an administrator session

First, wp_check_filetype_and_ext() looks up the file’s extension in the list returned by the upload_mimes filter. If svg is absent, WordPress rejects the upload with “Sorry, this file type is not permitted for security reasons.” Adding it to that array is the one-line change every blog post shows you.

Second — and this is the part the snippets omit — WordPress tries to confirm the file’s real type. For raster images it calls getimagesize() or finfo_file() and compares the result against the claimed extension. SVG has no binary magic number, so finfo on some systems reports text/plain, on others text/html, and on newer libmagic builds image/svg+xml. That inconsistency is why the same snippet works on one host and silently fails on another.

Third, nothing in core reads the XML. WordPress stores whatever bytes arrived. The file then lives under your document root and is served by your web server with the image/svg+xml content type. When a browser fetches an SVG through an <img> tag, script inside it does not execute — but the media library grid, an “open in new tab” click, or a direct link renders it as a document, and at that point any script inside runs on your origin, with your admin’s cookies, against your REST API. Creating a new administrator account takes one fetch() call.

So the honest framing is: allowing .svg uploads is allowing arbitrary first-party HTML-equivalent documents from whoever holds upload_files. If that set of people is exactly you, the risk is small. If it includes contributors, clients, or a front-end upload form, it is not.

Sanitizing changes the calculation but does not eliminate it. A sanitizer parses the XML, walks the tree and removes elements and attributes not on an allowlist. That reliably kills <script>, on* handlers, <foreignObject>, external entity declarations and javascript: URLs. It cannot promise immunity against a parser differential nobody has found yet, which is why the role restriction and the response headers below are worth adding on top rather than instead.

Step-by-step

  1. Decide which option applies before you change anything. Who holds upload_files is the whole question.

    Decision tree for whether a site should accept SVG uploads, branching on who holds the upload capability

  2. Install a sanitizing plugin rather than writing the filter yourself. Safe SVG is the common choice; it wraps the widely used svg-sanitizer PHP library, which does the allowlist-based DOM walk. Enshrined’s library is the same code most alternatives vendor, so “Safe SVG or equivalent” genuinely means equivalent here.

    wp plugin install safe-svg --activate

    Expected output ends with Plugin 'safe-svg' activated. and Success: Installed 1 of 1 plugins. The plugin adds the MIME type and hooks the sanitizer into wp_handle_upload_prefilter, so you do not also need an upload_mimes snippet. Adding one anyway is how people accidentally allow unsanitized uploads after later deactivating the plugin.

  3. Confirm the MIME type is now allowed. Ask WordPress directly instead of guessing.

    wp eval 'echo isset( get_allowed_mime_types()["svg"] ) ? get_allowed_mime_types()["svg"] : "not allowed";'

    You should see image/svg+xml. If it prints not allowed, the plugin is not active for the current user context, or another plugin is filtering upload_mimes later and overwriting the array.

  4. Restrict the allowance to administrators if you chose option 2. Put this in a site-specific plugin, not the theme.

    add_filter( 'upload_mimes', function ( $mimes ) {
        // Only administrators may upload SVG; everyone else keeps the default list.
        if ( ! current_user_can( 'manage_options' ) ) {
            unset( $mimes['svg'], $mimes['svgz'] );
        }
        return $mimes;
    }, 20 );

    Priority 20 runs after the sanitizing plugin’s own filter, so your removal wins. Test by logging in as an Editor: the upload should be refused with the standard message, while an Administrator’s upload still succeeds.

  5. Serve SVGs with the correct content type and defensive headers. Most web servers already map .svg correctly, but check, because a wrong type breaks rendering and a missing X-Content-Type-Options header lets a browser sniff its way into a worse outcome.

    curl -sI https://example.com/wp-content/uploads/2026/08/logo.svg | grep -i -E 'content-type|x-content-type|content-security'

    You want content-type: image/svg+xml. Adding X-Content-Type-Options: nosniff site-wide is cheap and worth doing. A Content-Security-Policy containing script-src 'self' does not help here — the SVG is on 'self'. If you want CSP to carry weight for uploaded files, the assets have to live on a different origin, which is option 3.

  6. Audit what is already in the library. If SVG was ever enabled with a raw snippet, assume nothing was checked.

    grep -rilE '<script|on(load|error|click|mouseover)=|<foreignObject|<!ENTITY|javascript:' \
      --include='*.svg' --include='*.svgz' wp-content/uploads/

    No output means no matches, which is the result you want. Every path it prints is a file to open and read before you decide whether it is a designer’s careless export or something deliberate. Note that .svgz files are gzipped, so grep will not see inside them — decompress those separately with gunzip -c before scanning.

  7. Fix the two display problems. WordPress cannot generate raster thumbnails from an SVG, so the grid shows a blank tile, and an SVG without width, height or a viewBox stretches to fill its container. Modern versions of Safe SVG handle both; if you are on a lean setup, the durable fix is upstream — export SVGs with an explicit viewBox and matching width and height attributes. An SVG that carries viewBox="0 0 240 80" and width="240" sizes predictably everywhere, including in editors that never learned about SVG.

Validate it works

Plant a marker and confirm it is gone. On staging, create a test file:

cat > /tmp/probe.svg <<'EOF'
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 40" width="120" height="40">
  <rect width="120" height="40" fill="#0b4d78"/>
  <script type="text/javascript">console.log('SH-PROBE-MARKER');</script>
</svg>
EOF

Upload it through the media library UI as an administrator — not with wp media import, which can take a different code path — then find where it landed and read it back:

wp post list --post_type=attachment --s=probe --field=ID | \
  xargs -I{} wp eval "echo get_attached_file({});"

Print the stored file and check for the marker:

grep -c 'SH-PROBE-MARKER' "$(wp post list --post_type=attachment --s=probe --field=ID | head -1 | xargs -I{} wp eval "echo get_attached_file({});")"

0 is the pass condition: the sanitizer parsed the file, dropped the <script> element and wrote back clean XML, and the rectangle still renders. If you get 1, the file was stored verbatim — the sanitizer is not running on this path, and you should treat SVG uploads as disabled until you find out why. Delete the probe attachment afterward.

Troubleshooting

“Sorry, this file type is not permitted for security reasons” even with the plugin active. Another plugin or a security suite is filtering upload_mimes at a later priority and rebuilding the array from scratch. Run the get_allowed_mime_types() check from step 3 while logged in as the affected user — a role-based restriction you forgot about behaves identically. Some managed hosts also enforce their own upload allowlist above WordPress; that one you cannot filter around.

The upload is rejected only on one server. This is the finfo mismatch. WordPress compares the real type it detected against the type registered for the extension, and older libmagic builds report SVG as text/plain or text/html. Confirm with file --mime-type logo.svg on the server. Sanitizing plugins normally paper over this by filtering wp_check_filetype_and_ext; if yours does not, that filter is the correct place to fix it — not a blanket exemption that skips type checking for every upload.

Thumbnails are blank in the media grid. Expected, not broken: there is no raster sub-size to show. The grid falls back to a generic file icon unless something inlines the SVG. Do not chase this by running thumbnail regeneration — there is nothing to regenerate from a vector source.

The SVG renders enormous in the editor or the front end. The file has no intrinsic size. Re-export it with viewBox plus width and height, or set explicit dimensions in CSS on the wrapper. Illustrator and Figma both emit sizeless SVGs under certain export presets, so this is usually fixable one step upstream of WordPress.

The file downloads instead of displaying. The server is sending application/octet-stream or text/plain. Fix the MIME map in the web server configuration rather than forcing a type in PHP — the file is served statically and never touches PHP.

When this is the wrong approach

If anyone other than a small, trusted, named set of people can upload media, do not enable SVG at all. That includes membership sites, multi-author publications, sites with front-end submission forms, and any client site where the agency does not control who gets an Editor account. In those cases the correct answer is boring: commit the SVGs to the theme or a site-specific plugin, where they pass through code review and version control, or serve them from a separate asset origin where a hostile file cannot reach your session cookies. This is the same reasoning that governs auditing the plugins you have already installed — the question is not whether the code is malicious today, but who can change it and how you would know.

Sanitizing is also not a substitute for keeping the plugin current. A sanitizer that has not been updated in two years is a parser with two years of unfixed bugs sitting directly in your upload path. If you enable this, put the plugin on whatever list you use to track update deadlines. And do not enable SVG uploads on a site where nobody has actually asked for them — the feature carries permanent maintenance cost in exchange for a convenience the design team may not need. Official guidance on WordPress’s file-handling model lives in the WordPress documentation.

Running WordPress that earns real money deserves an operator — Stack Harbor runs that stack under Enterprise WordPress; book an infrastructure consult.