WordPress 加入 SVG 支援

在 theme/functions.php 內加入

function wp_gaucho_cc_mime_types($mimes) {
$mimes[‘svg’] = ‘image/svg+xml’;
return $mimes;
}
add_filter(‘upload_mimes’, ‘wp_gaucho_cc_mime_types’);
function wp_gaucho_prepare_attachment_for_js_filter($response, $attachment, $meta){
if( $response[‘mime’] == ‘image/svg+xml’ && empty($response[‘sizes’]) ){
$svg_file_path = get_attached_file( $attachment->ID );

$orig_size = wp_gaucho_get_original_svg_size( $svg_file_path );

$response[‘sizes’] = array(
‘full’ => array(
‘url’ => $response[‘url’],
‘width’ => $orig_size[0],
‘height’ => $orig_size[1]
)
);

$arr = array( ‘width’ => $orig_size[0], ‘height’ => $orig_size[1] );
wp_update_attachment_metadata( $attachment->ID, $arr );
}
return $response;
}
//get width and height attributes of uploded SVG
function wp_gaucho_get_original_svg_size($file) {
$arr = array();
$xml_get = simplexml_load_file($file);
$xml_attrs = $xml_get->attributes();

$width = (string) $xml_attrs->width;
if ( empty($width) ) {
$width = ‘100%’;
}

$height = (string) $xml_attrs->height;
if ( empty($height) ) {
$height = ‘100%’;
}

$arr[] = $width;
$arr[] = $height;

return $arr;
}
add_filter(‘wp_prepare_attachment_for_js’, ‘wp_gaucho_prepare_attachment_for_js_filter’, 10, 3);

發佈留言