Show SVG Previews and Dimensions in the Media Library
Makes uploaded SVG files show a real preview in the Media Library grid and attachment details, and stores their width and height from the viewBox so they display at the right size in posts.
Opens WPIDE on
Code
add_filter( 'wp_generate_attachment_metadata', function ( $metadata, $attachment_id ) {
if ( 'image/svg+xml' !== get_post_mime_type( $attachment_id ) ) {
return $metadata;
}
$file = get_attached_file( $attachment_id );
$svg = $file && is_readable( $file ) ? (string) file_get_contents( $file, false, null, 0, 64 * KB_IN_BYTES ) : '';
if ( preg_match( '/viewBox=["\']\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)/i', $svg, $box ) ) {
$metadata['width'] = (int) round( (float) $box[1] );
$metadata['height'] = (int) round( (float) $box[2] );
} elseif ( preg_match( '/<svg[^>]*\swidth=["\']([\d.]+)[^>]*\sheight=["\']([\d.]+)/i', $svg, $size ) ) {
$metadata['width'] = (int) $size[1];
$metadata['height'] = (int) $size[2];
}
$metadata['file'] = _wp_relative_upload_path( $file );
return $metadata;
}, 10, 2 );
add_filter( 'wp_prepare_attachment_for_js', function ( $response ) {
if ( 'image/svg+xml' !== ( $response['mime'] ?? '' ) ) {
return $response;
}
$full = array(
'url' => $response['url'],
'width' => (int) ( $response['width'] ?? 0 ),
'height' => (int) ( $response['height'] ?? 0 ),
'orientation' => ( $response['height'] ?? 0 ) > ( $response['width'] ?? 0 ) ? 'portrait' : 'landscape',
);
$response['image'] = array( 'src' => $response['url'] );
$response['sizes'] = array( 'full' => $full, 'medium' => $full, 'thumbnail' => $full );
return $response;
} );
add_action( 'admin_head', function () {
echo '<style>.attachment-preview img[src$=".svg"],.media-modal img[src$=".svg"],td.media-icon img[src$=".svg"]{width:100%;height:auto;padding:8px;box-sizing:border-box}</style>';
} );
Notes
Only affects SVG files you are already allowed to upload; it does not enable SVG uploads by itself.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.