Display Post Attachments in a List

Attachment List

While building an order tracking system, where I used Custom Meta Boxes to collect and store custom data about each order, I had a need to be able to upload documents (such as invoices and authorisations) to each order and display them on the front end for authorised users to view.

In order to do this, I built a custom page template for my custom post type and used the wp_get_attachment_link function in conjunction with a get_posts query to retrieve all of the attachments on the given post and display them in a list with a link to each document.

Within the loop, I used the following snippet:

The first half of the snippet runs a get_posts query to find all of the post attachments whose parent is the post that we’re currently viewing (attachments are their own post type and have a parent if they are associated with a particular post).

The second half of the snippet takes that array and for each one, it runs through the wp_get_attachment_link function to retrieve the link to the attachment, using the file title as the link text.

The end result is that you can drop a list of post attachments into an unordered list for viewing, like in this screenshot:

Attachment List

You can also modify the wp_get_attachment_link arguments to do an array of different things, like displaying an icon depending on the file type.

One thought on “Display Post Attachments in a List”

  1. Nice snippet, I use this all the time for image sliders using similar arguments on get_posts and then using wp_get_attachment_url($post_attachments->ID).

Leave a Reply