Created
August 3, 2016 01:41
-
-
Save grok/e257ea85a492ab267fd1f0b28fdafe03 to your computer and use it in GitHub Desktop.
This is an example implementation of the patch for https://core.trac.wordpress.org/ticket/37549
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'wp_generate_attachment_metadata', __NAMESPACE__ . '\\update_attachment_metadata', 10, 2 ); | |
function update_attachment_metadata( $data, $attachment_id ) { | |
$dimensions = false; | |
$post = get_post( $attachment_id ); | |
$file = wp_get_attachment_url( $attachment_id ); | |
$path = get_attached_file( $attachment_id ); | |
// If we're dealing with an SVG -- this is probably empty. | |
// But, in the future it might not be and we should preserve that date. | |
$data = wp_get_attachment_metadata( $attachment_id ); | |
if( $post->post_mime_type !== 'image/svg+xml' ) { | |
return false; | |
} | |
$xml = simplexml_load_file( $file ); | |
$attributes = $xml->attributes(); | |
// Yay we have a proper viewport! | |
// This is the ideal way to get dimensions for the SVG. | |
if( isset( $attributes->width ) && isset( $attributes->height ) ) { | |
$dimensions = array( | |
'width' => $attributes->width, | |
'height' => $attributes->height | |
); | |
} | |
// Whelp... we don't have a viewport... time to hacky hacky? | |
// The viewBox attribute allows to specify that a given set of graphics | |
// stretch to fit a particular container element. | |
// The value of the viewBox attribute is a list of four numbers | |
// min-x, min-y, width and height, separated by whitespace and/or a comma, | |
// which specify a rectangle in user space which should be mapped to the | |
// bounds of the viewport established by the given element, taking into | |
// account attribute preserveAspectRatio. | |
// | |
// I do not believe it's a required attribute though... | |
// | |
// Source: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox | |
if( ! $dimensions ) { | |
$viewbox = explode( ' ', $attributes->viewBox ); | |
if( isset( $viewbox[ 2 ] ) && isset( $viewbox[ 3 ] ) ) { | |
$dimensions = array( | |
'width' => $viewbox[ 2 ], | |
'height' => $viewbox[ 3 ] | |
); | |
} | |
} | |
if( isset( $dimensions[ 'width' ] ) && isset( $dimensions[ 'height' ] ) ) { | |
if( is_array( $data ) ) { | |
$data = array_merge( $data, $dimensions ); | |
} else { | |
$data = $dimensions; | |
} | |
} | |
return $data; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment