Last active
June 1, 2025 18:49
-
-
Save chrishow/4f6322fd70a954f3d39cacf550b7408b to your computer and use it in GitHub Desktop.
FIx WordPress svg width and height attributes in wp_get_attachment_image_src()
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_get_attachment_image_src', function ($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; | |
} , 10, 4 ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment