A message was posted in the Etch Community about retrieving file information from the media library and exposing it on the front end. I had built something like this Brisck a few years ago, but I could not find the code so I asked ChatGPT and seconds later a working solution.
First, you add PHP to enable and expose the data to Etch.
<?php
add_filter(
'etch/dynamic_data/post',
function( $data, $post_id ) {
if ( 'attachment' !== get_post_type( $post_id ) ) {
return $data;
}
$path = get_attached_file( $post_id );
$url = wp_get_attachment_url( $post_id );
$mime = get_post_mime_type( $post_id );
$metadata = wp_get_attachment_metadata( $post_id );
$author = get_userdata( (int) get_post_field( 'post_author', $post_id ) );
$filename = $path ? wp_basename( $path ) : '';
$extension = $path ? strtolower( pathinfo( $path, PATHINFO_EXTENSION ) ) : '';
$filesize = $path && is_readable( $path ) ? filesize( $path ) : 0;
$data['file'] = [
'url' => $url ?: '',
'filename' => $filename,
'extension' => $extension,
'mime_type' => $mime ?: '',
'type' => $mime ? strtok( $mime, '/' ) : '',
'subtype' => $mime && str_contains( $mime, '/' )
? substr( $mime, strpos( $mime, '/' ) + 1 )
: '',
'size' => $filesize,
'size_formatted' => $filesize ? size_format( $filesize, 2 ) : '',
'date_added' => get_post_time( 'c', false, $post_id ),
'date_modified' => get_post_modified_time( 'c', false, $post_id ),
'author_id' => $author ? $author->ID : 0,
'author_name' => $author ? $author->display_name : '',
'width' => isset( $metadata['width'] )
? (int) $metadata['width']
: 0,
'height' => isset( $metadata['height'] )
? (int) $metadata['height']
: 0,
'caption' => wp_get_attachment_caption( $post_id ),
'alt' => (string) get_post_meta(
$post_id,
'_wp_attachment_image_alt',
true
),
];
return $data;
},
10,
2
);Then write a query
$query_args = [
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => $count ?? 20,
'orderby' => 'date',
'order' => 'DESC',
];Now you can loop through the items and expose the data you need. This is an example, and you can structure it any way you like.
<article class="file-card">
<h3>{item.title}</h3>
<dl class="file-card__details">
<div>
<dt>File name</dt>
<dd>{item.file.filename}</dd>
</div>
<div>
<dt>File type</dt>
<dd>{item.file.extension.toUpperCase()}</dd>
</div>
<div>
<dt>MIME type</dt>
<dd>{item.file.mime_type}</dd>
</div>
<div>
<dt>File size</dt>
<dd>{item.file.size_formatted}</dd>
</div>
<div>
<dt>Date added</dt>
<dd>{item.file.date_added.dateFormat("F j, Y")}</dd>
</div>
<div>
<dt>Author</dt>
<dd>{item.file.author_name}</dd>
</div>
{#if item.file.width}
<div>
<dt>Dimensions</dt>
<dd>{item.file.width} × {item.file.height} pixels</dd>
</div>
{/if}
</dl>
<a href="{item.file.url}">
Download {item.title}
</a>
</article>