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)".
Opens WPIDE on
Code
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 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.