Skip to content

Instantly share code, notes, and snippets.

@ritcheyer
Forked from Lewiscowles1986/lc-svg-upload.php
Last active August 29, 2015 14:19
Show Gist options
  • Save ritcheyer/48f1c186d6c403dca1ba to your computer and use it in GitHub Desktop.
Save ritcheyer/48f1c186d6c403dca1ba to your computer and use it in GitHub Desktop.
<?php
/*
Plugin Name: SVG Upload
Plugin URI: http://www.lewiscowles.co.uk
Description: Super PHP Plugin to add Full SVG Media support to WordPress, I should live in {$webroot}/wp-content/plugins/ folder ;)
Author: Lewis Cowles
Version: 1.0
Author URI: http://www.lewiscowles.co.uk/
*/
add_action('admin_init', 'add_svg_upload');
function add_svg_upload() {
add_filter('upload_mimes', function(){
$mimes['svg'] = 'image/svg+xml';
return $mimes;
});
ob_start();
add_action('shutdown', function() {
$final = '';
$ob_levels = count(ob_get_level());
for ($i = 0; $i < $ob_levels; $i++) {
$final .= ob_get_clean();
}
echo apply_filters('final_output', $final);
}, 0);
add_filter('final_output', function($content) {
$content = str_replace('<# } else if ( \'image\' === data.type && data.sizes && data.sizes.full ) { #>',
'<# } else if ( \'svg+xml\' === data.subtype ) { #>
<img class="details-image" src="{{ data.url }}" draggable="false" />
<# } else if ( \'image\' === data.type && data.sizes && data.sizes.full ) { #>',
$content
);
$content = str_replace(
'<# } else if ( \'image\' === data.type && data.sizes ) { #>',
'<# } else if ( \'svg+xml\' === data.subtype ) { #>
<div class="centered">
<img src="{{ data.url }}" class="thumbnail" draggable="false" />
</div>
<# } else if ( \'image\' === data.type && data.sizes ) { #>',
$content
);
return $content;
});
}
/*
* Logic Breakdown
* 1) We need the whole page, but only if we are in the backend (hence admin_init hook)
* 2) We would like to grab all output (ob_start within admin_init as nothing should echo before that, we should not interfere with things that do)
* 3) We want to grab the content on shutdown, concatenate all output buffers, then filter
* 4) Search for placeholders which should exist and replace the text
* Downsides
* 1) Not permanent fix (for perma fix WP core would need to be editable or native filtering added)
* 2) A bit resource munchy (it's locked to the admin side, so IMHO who cares)
* 3) This is just to get SVG into WP core... Luckily the find replace is that simple in /wp-includes/media-template.php (Patch it Mullenweg & Co!)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment