Skip to content

Instantly share code, notes, and snippets.

@benfrain
Created March 8, 2014 00:05
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save benfrain/9422862 to your computer and use it in GitHub Desktop.
Save benfrain/9422862 to your computer and use it in GitHub Desktop.
Allow SVG upload and preview to Media area of Wordpress (add this to functions.php)
function custom_mtypes( $m ){
$m['svg'] = 'image/svg+xml';
$m['svgz'] = 'image/svg+xml';
return $m;
}
add_filter( 'upload_mimes', 'custom_mtypes' );
@brandlinedigital
Copy link

The preview doesn't work.

@fadupla
Copy link

fadupla commented Apr 26, 2018

@brandlinedigital you would need more code to have the media preview to work (grid view, list view and single view) :

In your theme functions.php file :

/**
 * Add svg MIME type support
 *
 * @param $mimes
 *
 * @author fadupla
 * @return mixed
 */
function fadupla_mime_types( $mimes ) {
	$mimes['svg'] = 'image/svg+xml';

	return $mimes;
}

add_filter( 'upload_mimes', 'fadupla_mime_types' );

/**
 * Enqueue SVG javascript and stylesheet in admin
 * @author fadupla
 */

function fadupla_svg_enqueue_scripts( $hook ) {
	wp_enqueue_style( 'fadupla-svg-style', get_theme_file_uri( '/assets/css/svg.css' ) );
	wp_enqueue_script( 'fadupla-svg-script', get_theme_file_uri( '/assets/js/svg.js' ), 'jquery' );
	wp_localize_script( 'fadupla-svg-script', 'script_vars',
		array( 'AJAXurl' => admin_url( 'admin-ajax.php' ) ) );
}

add_action( 'admin_enqueue_scripts', 'fadupla_svg_enqueue_scripts' );


/**
 * Ajax get_attachment_url_media_library
 * @author fadupla
 */
function fadupla_get_attachment_url_media_library() {

	$url          = '';
	$attachmentID = isset( $_REQUEST['attachmentID'] ) ? $_REQUEST['attachmentID'] : '';
	if ( $attachmentID ) {
		$url = wp_get_attachment_url( $attachmentID );
	}

	echo $url;

	die();
}

add_action( 'wp_ajax_svg_get_attachment_url', 'fadupla_get_attachment_url_media_library' );

the assets/js/svg.js file :

var mediaGridObserver = new MutationObserver(function (mutations) {

    for (var i = 0; i < mutations.length; i++)
    {

        for (var j = 0; j < mutations[i].addedNodes.length; j++)
        {
            element = $(mutations[i].addedNodes[j]);

            if (element.attr('class'))
            {
                elementClass = element.attr('class');
                if (element.attr('class').indexOf('attachment') != -1)
                {

                    attachmentPreview = element.children('.attachment-preview');
                    if (attachmentPreview.length != 0)
                    {
                        if (attachmentPreview.attr('class').indexOf('subtype-svg+xml') != -1)
                        {
                            var handler = function (element) {

                                jQuery.ajax({

                                    url: script_vars.AJAXurl,
                                    type: "POST",
                                    dataType: 'html',
                                    data: {
                                        'action': 'svg_get_attachment_url',
                                        'attachmentID': element.attr('data-id')
                                    },
                                    success: function (data) {
                                        if (data)
                                        {
                                            element.find('img').attr('src', data);
                                            element.find('.filename').text('SVG Image');
                                        }
                                    }
                                });

                            }(element);

                        }
                    }
                }
            }
        }
    }
});

var attachmentPreviewObserver = new MutationObserver(function (mutations) {
    for (var i = 0; i < mutations.length; i++)
    {
        for (var j = 0; j < mutations[i].addedNodes.length; j++)
        {
            var element = $(mutations[i].addedNodes[j]);
            var onAttachmentPage = false;
            if ((element.hasClass('attachment-details')) || element.find('.attachment-details').length != 0)
            {
                onAttachmentPage = true;
            }

            if (onAttachmentPage == true)
            {
                var urlLabel = element.find('label[data-setting="url"]');
                if (urlLabel.length != 0)
                {
                    var value = urlLabel.find('input').val();
                    element.find('.details-image').attr('src', value);
                }
            }
        }
    }
});

$(document).ready(function () {

    mediaGridObserver.observe(document.body, {
        childList: true,
        subtree: true
    });

    attachmentPreviewObserver.observe(document.body, {
        childList: true,
        subtree: true
    });


});

the assets/css/svg.css file :

img[src*='.svg'] {
    width: 100%;
    height: auto;
}

@piotrku
Copy link

piotrku commented Aug 14, 2020

I had to change:
$(
to
jQuery(
and fix a little image positioning
but otherwise works great, thanks man!

@nicholascourage
Copy link

For WordPress 5.7.2 var urlLabel = element.find('label[data-setting="url"]'); needs to be updated to : var urlLabel = element.find('span[data-setting="url"]');

I found that out the hardway but otherwise thank you very much :)

SitePoint has a similiar description that follows this way of doing it too which I also found very helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment