Created
February 6, 2017 08:49
-
-
Save malthejorgensen/4ec565f444c969731c71089afd70cbde to your computer and use it in GitHub Desktop.
svg-support (Wordpress plugin) - external URL fix
This file contains 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 | |
/** | |
* Display SVG in attachment modal | |
*/ | |
if ( ! defined( 'ABSPATH' ) ) { | |
exit; // Exit if accessed directly | |
} | |
function bodhi_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 ) ) { | |
// In the case where the SVG is located on an external URL | |
// (not on this server), we use the URL instead of the path | |
$svg_path = $response[ 'url' ]; | |
} | |
$dimensions = bodhi_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; | |
} | |
add_filter( 'wp_prepare_attachment_for_js', 'bodhi_svgs_response_for_svg', 10, 3 ); | |
function bodhi_svgs_get_dimensions( $svg ) { | |
$svg = simplexml_load_file( $svg ); | |
$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