Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add SVG support to Wordpress Media library view + upload SVG
<?php
/**
* Add support to SVG in WP media viewer
*/
function svg_meta_data_support($data, $id){
$attachment = get_post($id); // Filter makes sure that the post is an attachment
$mime_type = $attachment->post_mime_type; // The attachment mime_type
//If the attachment is an svg
if($mime_type && $mime_type == 'image/svg+xml'){
//If the svg metadata are empty or the width is empty or the height is empty
//then get the attributes from xml.
if(empty($data) || empty($data['width']) || empty($data['height'])){
$xml = simplexml_load_file(wp_get_attachment_url($id));
$attr = $xml->attributes();
$viewbox = explode(' ', $attr->viewBox);
$data['width'] = isset($attr->width) && preg_match('/\d+/', $attr->width, $value) ? (int) $value[0] : (count($viewbox) == 4 ? (int) $viewbox[2] : null);
$data['height'] = isset($attr->height) && preg_match('/\d+/', $attr->height, $value) ? (int) $value[0] : (count($viewbox) == 4 ? (int) $viewbox[3] : null);
}
}
return $data;
}
add_filter('wp_update_attachment_metadata', 'svg_meta_data_support', 10, 2);
/**
* Add mime supporttypes,
* SVG
*/
function vt_add_mime_types_support($file_types){
$new_filetypes = array();
$new_filetypes['svg'] = 'image/svg+xml';
$file_types = array_merge($file_types, $new_filetypes );
return $file_types;
}
add_action('upload_mimes', 'vt_add_mime_types_support');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment