Skip to content

Instantly share code, notes, and snippets.

@DevWael
Created June 4, 2020 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DevWael/bab374eaa7f8e6f6889fd66c8cf263a3 to your computer and use it in GitHub Desktop.
Save DevWael/bab374eaa7f8e6f6889fd66c8cf263a3 to your computer and use it in GitHub Desktop.
Allow SVG Upload in WordPress Media Uploader
<?php
//Allow SVG upload
add_filter( 'upload_mimes', 'inn_mime_types' );
function inn_mime_types( $mimes ) {
$mimes['svg'] = 'image/svg+xml';
$mimes['svgz'] = 'image/svg+xml';
return $mimes;
}
//display SVG Images in wp media uploader proberly
add_filter( 'wp_prepare_attachment_for_js', 'inn_svgs_response_for_svg', 10, 3 );
function inn_svgs_response_for_svg( $response, $attachment, $meta ) {
if ( $response['mime'] == 'image/svg+xml' && empty( $response['sizes'] ) ) {
$svg_path = get_attached_file( $attachment->ID );
if ( ! file_exists( $svg_path ) ) {
// If SVG is external, use the URL instead of the path
$svg_path = $response['url'];
}
$dimensions = inn_svgs_get_dimensions( $svg_path );
$response['sizes'] = array(
'full' => array(
'url' => $response['url'],
'width' => $dimensions->width,
'height' => $dimensions->height,
'orientation' => $dimensions->width > $dimensions->height ? 'landscape' : 'portrait'
)
);
}
return $response;
}
function inn_svgs_get_dimensions( $svg ) {
$svg = simplexml_load_file( $svg );
if ( $svg === false ) {
$width = '0';
$height = '0';
} else {
$attributes = $svg->attributes();
$width = (string) $attributes->width;
$height = (string) $attributes->height;
}
return (object) array( 'width' => $width, 'height' => $height );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment