Why WordPress Disables SVG by Default
Every other image format WordPress accepts — JPEG, PNG, WebP, GIF — is pixel data. There's no way to hide executable code inside a JPEG that a browser will run. SVG is different: it's an XML document, and XML can contain markup a browser will actually execute. A malicious SVG can carry:
- A
<script>element with arbitrary JavaScript, which runs the moment the SVG is opened directly or embedded as an<img>in some contexts. on*event handler attributes —onload,onmouseover, and similar — attached to any SVG element.- A
<foreignObject>element, which can embed entire HTML documents inside the SVG. - External entity references that can be abused for XXE (XML External Entity) attacks, potentially reading server files the attacker shouldn't have access to.
Given that any logged-in user with upload permission could otherwise plant one of these, WordPress core's decision to block SVG by default is the right call for most sites. Enabling it safely means adding back the sanitization WordPress deliberately doesn't do for you.
Add every snippet below to a site-specific plugin file, not your theme's functions.php — this is security logic, not presentation, and it should survive a theme change.
1. Enable the MIME Type — Restricted to Trusted Roles
The first step is telling WordPress that .svg is an acceptable upload extension. Doing this alone, for every user, is the mistake most quick tutorials make — pair it with a capability check so only roles you trust (typically Administrators, or Editors if you extend the check) can upload SVGs at all. Restricting who can upload is genuinely your strongest layer of defense, arguably more important than the sanitization step that follows.
Where to insert: your site-specific plugin file.
- Paste the snippet below into your plugin file.
- Log in as an Administrator and confirm .svg files now appear as an allowed type in Media → Add New.
- Log in as a lower-privileged role (Author or Contributor) and confirm SVG upload is still rejected for that account.
function enable_svg_upload_for_admins($mimes) {
if (current_user_can('manage_options')) {
$mimes['svg'] = 'image/svg+xml';
}
return $mimes;
}
add_filter('upload_mimes', 'enable_svg_upload_for_admins');
2. Fix WordPress's File Type Validation for SVG
WordPress runs every upload through an additional filetype/extension consistency check that often flags valid SVGs as suspicious, since SVG doesn't have the binary file signature WordPress's checker expects from an image. Without this fix, some SVG uploads get silently rejected even after Step 1.
Where to insert: your site-specific plugin file.
- Paste the snippet below into your plugin file.
- Try uploading a plain, valid SVG file and confirm it's accepted without a "sorry, this file type is not permitted" error.
function fix_svg_filetype_check($data, $file, $filename, $mimes) {
if (empty($data['type'])) {
$wp_filetype = wp_check_filetype($filename, $mimes);
if ($wp_filetype['ext'] === 'svg') {
$data['ext'] = 'svg';
$data['type'] = 'image/svg+xml';
}
}
return $data;
}
add_filter('wp_check_filetype_and_ext', 'fix_svg_filetype_check', 10, 4);
3. Sanitize Every SVG on Upload (the Critical Part)
This is the step that actually protects your site. It runs on every SVG at the moment of upload, strips out the specific patterns covered in the first section — script tags, event handler attributes, foreignObject blocks, and external entity declarations — and rejects the file outright if it doesn't look like a valid SVG to begin with.
Where to insert: your site-specific plugin file, alongside the two snippets above.
- Paste the snippet below into your plugin file.
- Create a test file called test-malicious.svg containing a basic SVG shape plus a
<script>alert('xss')</script>tag, and upload it as your Administrator account. - Open the uploaded file's URL directly in your browser and confirm no alert box appears — the script tag should have been stripped before the file was saved.
- View the uploaded SVG's contents (via FTP or file manager) and confirm the
<script>tag is genuinely gone from the saved file, not just visually inert.
function sanitize_svg_upload($file) {
if ($file['type'] === 'image/svg+xml') {
$svg_content = file_get_contents($file['tmp_name']);
// Reject anything that doesn't even look like an SVG
if (stripos($svg_content, '<svg') === false) {
$file['error'] = 'This file does not appear to be a valid SVG.';
return $file;
}
// Strip <script> elements entirely
$svg_content = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $svg_content);
// Strip on* event handler attributes (onload, onclick, onmouseover, etc.)
$svg_content = preg_replace('/\s*on\w+\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+)/i', '', $svg_content);
// Strip javascript: URIs from href / xlink:href attributes
$svg_content = preg_replace('/(xlink:href|href)\s*=\s*["\']javascript:[^"\']*["\']/i', '', $svg_content);
// Strip <foreignObject> blocks, which can embed arbitrary HTML
$svg_content = preg_replace('/<foreignObject\b[^>]*>(.*?)<\/foreignObject>/is', '', $svg_content);
// Strip DOCTYPE and ENTITY declarations (defense against XXE-style payloads)
$svg_content = preg_replace('/<!DOCTYPE[^>]*>/i', '', $svg_content);
$svg_content = preg_replace('/<!ENTITY[^>]*>/i', '', $svg_content);
file_put_contents($file['tmp_name'], $svg_content);
}
return $file;
}
add_filter('wp_handle_upload_prefilter', 'sanitize_svg_upload');
Be honest with yourself about what this does and doesn't guarantee. Regex-based stripping is a solid baseline defense against the common, well-known SVG attack patterns, but it is not a substitute for a proper XML-aware sanitization library — a sufficiently creative payload using unusual encoding or nested structures could theoretically slip past pattern matching. If SVG uploads will come from anyone outside your own trusted team (client-submitted logos, for example), consider installing a dedicated sanitization library like enshrined/svg-sanitize via Composer instead of relying on regex alone. For a small team of trusted admins uploading their own icons and logos, the combination of Step 1's role restriction plus this sanitizer is a reasonable, practical balance.
4. Fix Broken Media Library Thumbnails
PHP's getimagesize() function, which WordPress normally uses to read an image's width and height for the Media Library, doesn't understand SVG at all — so uploaded SVGs often show as a generic broken-image icon or a 0×0 dimension in the grid view even after uploading successfully. This snippet reads the dimensions directly from the SVG's own viewBox attribute instead.
Where to insert: your site-specific plugin file.
- Paste the snippet below into your plugin file.
- Upload a new SVG file (existing ones won't be retroactively fixed unless you regenerate their metadata).
- Open Media → Library in grid view and confirm the SVG now shows an actual preview instead of a broken icon.
function fix_svg_media_thumbnail($metadata, $attachment_id) {
if (get_post_mime_type($attachment_id) === 'image/svg+xml') {
$svg_path = get_attached_file($attachment_id);
$svg_content = file_get_contents($svg_path);
if (preg_match('/viewBox=["\']0 0 ([\d.]+) ([\d.]+)["\']/i', $svg_content, $matches)) {
$metadata['width'] = (int) $matches[1];
$metadata['height'] = (int) $matches[2];
} else {
$metadata['width'] = 100;
$metadata['height'] = 100;
}
}
return $metadata;
}
add_filter('wp_generate_attachment_metadata', 'fix_svg_media_thumbnail', 10, 2);
Final Checklist
- SVG MIME type enabled only for roles you actually trust — verified a lower-privileged account still can't upload one.
- File type validation fixed so legitimate SVGs aren't silently rejected.
- Sanitizer tested against a deliberately malicious test SVG containing a script tag, and confirmed the script was stripped from the saved file.
- Media Library grid view confirmed showing real SVG previews instead of broken icons.
- Considered whether a dedicated sanitization library is warranted, based on who's actually allowed to upload SVGs on your site.
The combination of role restriction plus upload-time sanitization is what turns "enabling SVG" from a real vulnerability into a reasonably safe, deliberate feature — skip either one, and you're back to the exact risk WordPress disabled SVG to avoid in the first place.
Comments & Feature Requests
0 Found a bug, or want a new tool? Let us know below.
comments_no_comments