Skip to content

Instantly share code, notes, and snippets.

@johanguse
Last active December 22, 2021 17:25
Show Gist options
  • Save johanguse/8fb78c3e02deffe5bb2f1ff816a35ae9 to your computer and use it in GitHub Desktop.
Save johanguse/8fb78c3e02deffe5bb2f1ff816a35ae9 to your computer and use it in GitHub Desktop.
Add width and height SVG upload on WordPress
/* ------------------------------------------------------------------------------- */
/* Add media data (width and height) to SVG upload
/* https://wordpress.stackexchange.com/a/256701/164915
/* Alternative: https://wordpress.org/plugins/enable-svg-uploads/
/* ------------------------------------------------------------------------------- */
function svg_meta_data($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 == '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', 10, 2);
/* ------------------------------------------------------------------------------- */
/* Edit get_attachment_image to add width and height on print
/* https://wordpress.stackexchange.com/a/255634/164915
/* ------------------------------------------------------------------------------- */
function fix_wp_get_attachment_image_svg($image, $attachment_id, $size, $icon) {
if (is_array($image) && preg_match('/\.svg$/i', $image[0]) && $image[1] <= 1) {
if(is_array($size)) {
$image[1] = $size[0];
$image[2] = $size[1];
} elseif(($xml = simplexml_load_file($image[0])) !== false) {
$attr = $xml->attributes();
$viewbox = explode(' ', $attr->viewBox);
$image[1] = isset($attr->width) && preg_match('/\d+/', $attr->width, $value) ? (int) $value[0] : (count($viewbox) == 4 ? (int) $viewbox[2] : null);
$image[2] = isset($attr->height) && preg_match('/\d+/', $attr->height, $value) ? (int) $value[0] : (count($viewbox) == 4 ? (int) $viewbox[3] : null);
} else {
$image[1] = $image[2] = null;
}
}
return $image;
}
add_filter( 'wp_get_attachment_image_src', 'fix_wp_get_attachment_image_svg', 10, 4 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment