# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Media](https://wpide.com/library/category/media/)
- Tags: svg, media-library, images
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/media-svg-previews/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Show SVG Previews and Dimensions in the Media Library" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
