Join

Conditionally Allow SVG Uploads

Don't want to mess with code snippets? This is a feature of MyListing Pro.

Instructions

  1. Create a new PHP code snippet.
  2. Copy the contents of code snippet below.
  3. Paste the contents into your code snippet.
  4. Review any notes that I’ve provided.
  5. Save and enable the code snippet.
  6. Test.

Snippet

WordPress blocks SVG uploads by default, so you end up converting images to a different format to get around “file type not allowed” errors.

The code snippet below lets you add SVGs to the media library like any other image.

PHP
add_filter("upload_mimes", function ($mimes) {
    $mimes["svg"] = "image/svg+xml";
        return $mimes;
    });

add_filter("wp_check_filetype_and_ext", function ($result, $file, $filename, $mimes) {
    if (!$result["ext"] || !$result["type"]) {
        $filetype = wp_check_filetype($filename, $mimes);
        $ext = $filetype["ext"];
        $type = $filetype["type"];
        $allowed_types = [
            "svg" => [
                "image/svg+xml"
            ],
        ];
        if (isset($allowed_types[$ext]) && in_array($type, $allowed_types[$ext])) {
            $result = [
                "ext" => $ext,
                "type" => $type,
                "proper_filename" => $filename
            ];
        }
    }
    return $result;
}, 10, 4);