Attached Files List Shortcode
Adds an [attached_files] shortcode that lists every PDF, document or other file uploaded to the current post as download links with file type and size, ideal for resources and meeting minutes.
Opens WPIDE on
Code
add_action( 'init', function () {
add_shortcode( 'attached_files', function ( $atts ) {
$atts = shortcode_atts( array( 'type' => '', 'title' => '', 'images' => 'no', 'id' => 0 ), $atts, 'attached_files' );
$post_id = $atts['id'] ? absint( $atts['id'] ) : get_the_ID();
if ( ! $post_id ) {
return '';
}
$files = get_children( array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'post_mime_type' => $atts['type'] ? sanitize_mime_type( $atts['type'] ) : '',
'orderby' => 'menu_order title',
'order' => 'ASC',
'numberposts' => 100,
) );
if ( 'yes' !== $atts['images'] ) {
$files = array_filter( $files, function ( $file ) {
return 0 !== strpos( $file->post_mime_type, 'image/' );
} );
}
if ( ! $files ) {
return '';
}
$html = '' !== $atts['title'] ? '<h3 class="wpide-files-title">' . esc_html( $atts['title'] ) . '</h3>' : '';
$html .= '<ul class="wpide-attached-files">';
foreach ( $files as $file ) {
$path = get_attached_file( $file->ID );
$meta = wp_get_attachment_metadata( $file->ID );
$size = ! empty( $meta['filesize'] ) ? (int) $meta['filesize'] : ( $path && file_exists( $path ) ? filesize( $path ) : 0 );
$html .= sprintf(
'<li><a href="%s" download>%s</a> <small>(%s%s)</small></li>',
esc_url( wp_get_attachment_url( $file->ID ) ),
esc_html( get_the_title( $file ) ),
esc_html( strtoupper( pathinfo( (string) $path, PATHINFO_EXTENSION ) ) ),
$size ? esc_html( ', ' . size_format( $size, 1 ) ) : ''
);
}
return $html . '</ul>';
} );
} );
Notes
Example [attached_files type="application/pdf" title="Downloads"]; images are skipped unless you add images="yes".
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.