# Download Button Shortcode With File Size

> Adds a [download_button] shortcode that turns a Media Library file into a download button showing the file type and size, such as "Brochure (PDF, 2.4 MB)".

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: shortcodes, downloads, media
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/download-button-shortcode/

## Code

```php
add_action( 'init', function () {
    add_shortcode( 'download_button', function ( $atts ) {
        $atts = shortcode_atts( array( 'id' => 0, 'text' => '' ), $atts, 'download_button' );
        $id   = absint( $atts['id'] );
        if ( ! $id || 'attachment' !== get_post_type( $id ) ) {
            return '';
        }

        $url  = wp_get_attachment_url( $id );
        $file = get_attached_file( $id );
        $meta = wp_get_attachment_metadata( $id );
        $size = ! empty( $meta['filesize'] ) ? (int) $meta['filesize'] : ( $file && file_exists( $file ) ? filesize( $file ) : 0 );
        $type = strtoupper( pathinfo( (string) $url, PATHINFO_EXTENSION ) );
        $text = '' !== $atts['text'] ? $atts['text'] : get_the_title( $id );

        return sprintf(
            '<a class="wp-element-button wpide-download" href="%s" download>%s <span class="wpide-download-meta">(%s%s)</span></a>',
            esc_url( $url ),
            esc_html( $text ),
            esc_html( $type ),
            $size ? esc_html( ', ' . size_format( $size, 1 ) ) : ''
        );
    } );
} );
```

## Notes

Example [download_button id="123" text="Get the brochure"]; find the ID in the Media Library address bar when you open the file.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Download Button Shortcode With File Size" 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/
