How to Enable SVG Uploads in WordPress

How to Enable SVG Uploads in WordPress by Editing functions.php

Introduction

SVG (Scalable Vector Graphics) is a popular image format for logos, icons, and other graphics because of its scalability without losing quality. However, WordPress restricts uploading SVGs due to security risks. In this post, I’ll show you how to allow SVG uploads safely by adding custom code to the functions.php file of your WordPress theme.

Step 1: Open Your Theme’s functions.php File

  1. Login to your WordPress Dashboard.
  2. Go to Appearance > Theme File Editor.
  3. From the right panel, select the functions.php file of your active theme.

Step 2: Add the Code to Enable SVG Uploads

Copy the code below and paste it at the end of your functions.php file.



// Allow SVG uploads in WordPress media library.

function allow_svg_upload($mimes) {

    $mimes['svg'] = 'image/svg+xml';

    return $mimes;

}

add_filter('upload_mimes', 'allow_svg_upload');

// Sanitize SVG uploads to ensure valid file type.

function sanitize_svg($data, $file, $filename, $mimes) {

    if (strpos($filename, '.svg') !== false) {

        $data['type'] = 'image/svg+xml';

        $data['ext']  = 'svg';

    }

    return $data;

}

add_filter('wp_check_filetype_and_ext', 'sanitize_svg', 10, 4);

            

Step 3: Save the Changes

After pasting the code, click the Update File button to save your changes.

Step 4: Test the SVG Upload

  1. Go to Media > Add New in the WordPress dashboard.
  2. Upload an SVG file to confirm that it works!

Optional: Restrict SVG Uploads to Administrators Only

If you want only administrators to upload SVG files, modify the code as shown below:



function allow_svg_upload($mimes) {

    if (current_user_can('administrator')) {

        $mimes['svg'] = 'image/svg+xml';

    }

    return $mimes;

}

add_filter('upload_mimes', 'allow_svg_upload');

            

Conclusion

By adding the above code to your functions.php file, you can now upload SVG files in WordPress without any issues. This solution ensures a smooth workflow with your media library while keeping your site secure. Happy uploading!