Enable SVG support for WordPress to allow uploading SVG images

SVG as a universal vector graphic format, has been supported by mainstream browsers, as of the date of this article, WordPress has not built-in SVG support, users can not directly upload SVG images to the WordPress post or media library, it is really incomprehensible. Although allowing embedded JavaScript code will bring some security issues, but it is not without a solution, if only because of this point and does not support SVG, is really a bit of a choke.

The good thing is that WordPress is an open platform, and although WordPress doesn't support uploading SVG images by default, there are a few things we can do to add this functionality to our site.

Adding SVG Support to WordPress via Code

Below is the code that allows SVG images to be uploaded in WordPress, simply add it to the theme's functions.php file or plugin file to enable SVG support for WordPress.

add_filter('wp_check_filetype_and_ext', function ($data, $file, $filename, $mimes)
{
    global $wp_version;

    if ($wp_version !== '4.7.1') {
        return $data;
    }

    $filetype = wp_check_filetype($filename, $mimes);

    return [
        'ext'             => $filetype[ 'ext' ],
        'type'            => $filetype[ 'type' ],
        'proper_filename' => $data[ 'proper_filename' ],
    ];

}, 10, 4);


add_filter('upload_mimes', function ($mimes)
{
    $mimes[ 'svg' ] = 'image/svg+xml';

    return $mimes;
});


add_action('admin_head', function ()
{
    echo '<style>
        .attachment-266x266, .thumbnail img {
             width: 100% !important;
             height: auto !important;
        }
        </style>';
});

Using this method to add SVG support to WordPress has no security checks and is not recommended for multi-user WordPress sites.

Enabling SVG Support for WordPress via Plugins

utilizationSafe SVG pluginAdding SVG support to WordPress is simple method and it is recommended that all of you use this method for this purpose. This plugin, apart from enabling WordPress support, will also clean and validate the uploaded SVG files to stop SVG vulnerabilities that may affect your website.

The Safe SVG plugin's safe handling feature is provided by thesvg-sanitizerlibrary implementation, if you have code cleanliness and want to integrate SVG support in your own theme or plugin, you can refer to Safe SVG plugin to implement safe handling features.

Other ways to enable SVG support for WordPress

In addition, the popular Elementor editor also has built-in support for enabling SVG support, but it seems that you can only upload SVG in the Elementor editor, not in the default media library.

If you have other ways to enable SVG support for WordPress, feel free to suggest them in the comments of this article.

Related Posts

Leave a Reply

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