Why Your WordPress Site Needs SVG
WordPress blocks SVG uploads by default for security reasons, but scalable vector graphics are smaller, sharper on any screen, and perfect for logos, icons, and illustrations. An SVG file that is 50 KB as a PNG becomes just 5 KB as an SVG, cutting image bandwidth by 90 percent. This is especially important for international sites where data costs money. The tradeoff is real: SVG files can contain malicious JavaScript if uploaded carelessly. This guide shows you how to enable SVG safely while protecting your site from injection attacks and maintaining visitor trust.
The Risk and Why It Matters
An attacker could upload an SVG with embedded JavaScript that runs when you view it in WordPress. SVG files are actually XML documents that can contain event handlers and script tags. A malicious SVG can steal admin cookies, redirect visitors, or inject advertising into your site. Sanitizing SVGs requires more than a simple file-type check. You must either use a vetted plugin or write strict filters that remove all potentially dangerous code. The risk is higher if your site allows multiple users to upload media or if you accept user-submitted graphics from your audience.
WordPress core developers decided to block SVG by default because of past security vulnerabilities. In 2015, a researcher demonstrated how malicious SVGs could be used to steal admin credentials through stored XSS (cross-site scripting) attacks. Even in 2024, new SVG attack vectors emerge regularly as browsers add new features. The WordPress security team continues to recommend extreme caution when enabling SVG support, especially on multi-user sites or e-commerce stores.
Common SVG Attack Vectors Explained
Understanding specific attack methods helps you grasp why naive SVG filtering fails. Script tag injection is the most direct: an attacker embeds <script>alert(‘hacked’)</script> directly in the SVG XML. Event handler injection uses onclick, onload, or onerror attributes to trigger JavaScript when a user views the image in certain browsers. A single line like <circle onload=”fetch(‘/admin/steal-data’)”> can steal data when rendered.
Foreign Namespace Injection exploits XML namespaces to hide malicious code in attributes that simple regex filters miss. Data URI schemes can embed JavaScript directly: <image href=”data:text/html,<script>…”>. Animated SVGs with JavaScript triggers can execute code on loop. XSLT processing instructions can transform the SVG into executable code on certain server configurations. Browser-based decompression attacks can use embedded deflate streams to hide payloads from text-based scanners.
This is why a simple regex check for “<script” is insufficient. Professional SVG sanitization requires parsing the full XML tree, understanding namespace contexts, and stripping dangerous elements comprehensively, not just searching for known strings.
Method 1: Use a Whitelist Filter in functions.php
Add this code to your theme’s functions.php file or create a custom plugin:
function allow_svg_upload( $mimes ) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter( 'upload_mimes', 'allow_svg_upload' );
This allows SVG files to upload, but does not sanitize them. Only use this if you are the sole uploader and fully trust the source. This approach is fastest to implement but riskiest. Every time you enable a mime type, you are trusting that the uploader will not accidentally introduce malicious files. This method works best for solo bloggers who manage all media uploads personally.
Be aware that this approach offers zero protection if your hosting account is compromised or if a plugin vulnerability allows unauthorized file uploads. Even if you trust your current users, any future plugin or theme update could introduce a vulnerability that allows an attacker to upload SVGs directly to your server. For this reason, this method should only be used on single-admin sites with strong password policies and regular security audits.
Method 2: Safe SVG Upload with Sanitization
For a more secure setup, add a sanitization filter that strips out scripts and potentially harmful attributes:
function allow_svg_upload_safe( $data, $file, $filename, $mimes ) {
if ( substr( $filename, -3 ) === 'svg' ) {
if ( preg_match( '/
return false;
}
if ( preg_match( '/on\w+\s*=/i', file_get_contents( $file ) ) ) {
return false;
}
}
return $data;
}
add_filter( 'wp_check_filetype_and_ext', 'allow_svg_upload_safe', 10, 4 );
This checks for script tags and event handlers (onclick, onload, etc.) before allowing the upload. However, sophisticated attacks may bypass simple regex checks. Attackers can use encoded event handlers, nested CDATA sections, and other XML tricks to slip malicious code past basic filters. For e-commerce sites or multi-user WordPress installations, a dedicated plugin with comprehensive sanitization is safer and more reliable than custom regex.
A more thorough approach involves using the DOMPurify library or similar XML parsing to understand the full structure. However, maintaining such code requires security expertise and ongoing updates as new attack vectors emerge. Most WordPress sites lack the resources to keep custom sanitization code secure long-term.
Method 3: Restrict SVG Uploads to Administrators Only
Limit who can upload SVGs by adding this code:
function restrict_svg_upload( $caps, $cap, $user_id ) {
if ( $cap === 'upload_files' && ! user_can( $user_id, 'manage_options' ) ) {
$caps[] = 'do_not_allow';
}
return $caps;
}
add_filter( 'map_meta_cap', 'restrict_svg_upload', 10, 3 );
This ensures only logged-in administrators can upload any files at all, including SVGs. It is the safest approach for team sites and agencies. By limiting uploads to administrators, you reduce the attack surface to trusted users only. This does not sanitize SVG files, but it assumes your admins will not upload malicious content intentionally. It is not fool-proof if an admin account is compromised, but it prevents guest and contributor attacks entirely.
In practice, this method works well for corporate WordPress sites where a central communications team manages all media. Editorial teams with 5-10 trusted people uploading content can safely use this restriction without losing productivity. Content contributors use admin-managed shared drive folders or brand asset libraries instead of uploading directly to WordPress.
Method 4: Use ReadyGo Toolkit for One-Click Safety
ReadyGo Toolkit (free) has a built-in module that safely enables SVG uploads with automatic sanitization. Toggle it on, upload with confidence, and let the plugin handle script removal and attribute filtering in the background. No code required. The plugin uses a comprehensive sanitization library that removes dangerous elements while preserving the visual integrity of your SVG files. You get the security of method 2 with the ease of method 1.
ReadyGo Toolkit’s SVG module automatically updates its sanitization rules as new attack vectors emerge, eliminating the maintenance burden of keeping custom code secure. The plugin integrates seamlessly with WordPress file upload dialogs, media library browsing, and drag-and-drop uploads. Store owners can grant media upload permissions to clients or team members without security anxiety. The plugin logs sanitization actions, so you can audit what was filtered if a suspicious upload occurs.
How to Display SVGs in WordPress
Once enabled, SVGs appear in the media library like any other image. Insert them via the block editor or use the standard img tag:
<img src="https://yoursite.com/wp-content/uploads/logo.svg" alt="Logo" />
For CSS background images:
.header-logo {
background-image: url('https://yoursite.com/wp-content/uploads/logo.svg');
}
SVGs scale infinitely without pixelation, making them ideal for responsive designs. A single SVG file works at any size: 100px, 500px, or 5000px. This saves bandwidth and time spent creating multiple image versions for different screen sizes. Your logo stays crisp on mobile phones and 4K displays without multiple assets.
You can also embed SVGs inline directly in HTML for more control:
<svg viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="blue" />
</svg>
Inline SVGs allow CSS styling and JavaScript interaction. You can change colors on hover, animate elements, or respond to user clicks. This approach is ideal for interactive icons or complex graphics that need to adapt based on user actions or theme settings. However, inline SVGs increase HTML file size, so use them selectively for critical graphics only.
Performance Benefits
A typical PNG logo at 200x200px is 25-50 KB. The same logo as SVG is 2-5 KB. On a site with 100 icons in the UI, you save 2-5 MB of image downloads per visitor. For sites with limited hosting bandwidth or many international visitors in regions with expensive data, this difference is significant. SVGs also render faster because they are drawn by the browser rather than decompressed from a bitmap. Modern browsers cache SVG definitions in memory, making subsequent uses even faster.
Real-world performance gains: An e-commerce store with 500 product images at 50 KB each (25 MB total) could reduce that to 5 MB if those images were icons or illustrations converted to SVG. On a site with 10,000 monthly visitors, that is 250 GB of bandwidth saved per month. At typical hosting rates, that translates to $25-50 in reduced hosting costs monthly, or $300-600 annually. For sites with tight hosting budgets or serving global audiences, this savings justifies the security effort.
Frequently Asked Questions
Will SVGs work on all browsers?
Yes. All modern browsers support inline SVG images. Internet Explorer 8 and older do not, but those browsers represent less than 0.5 percent of global traffic and are no longer worth supporting.
Can I use SVGs with shortcodes?
Yes, but avoid allowing user-generated SVG shortcodes. Stick to admin-uploaded SVGs only and display them via simple img tags or CSS. User-generated SVG shortcodes could lead to injection attacks.
Is it safe to enable SVG uploads for all users?
No. Always restrict SVG uploads to administrators or use a plugin with robust sanitization. Multi-user sites face significantly higher risk from malicious uploads.
Can I edit SVGs in WordPress?
WordPress does not include an SVG editor. To modify SVGs, use a dedicated tool like Inkscape (free), Adobe Illustrator, or Figma. Download the SVG, edit it, and re-upload it to WordPress.
Will SVG images show up in Google Images?
Yes, Google indexes SVG images just like PNG or JPG. Make sure to include descriptive alt text and file names for best SEO results.
