Let’s say we have a list of downloadable items listed on a post or page, case studies for example. To help the end user understand what they will be downloading we’d like to display a file type adjacent to a download link.

e.g. Click to Download | PDF

Background: In this particular example our Case Studies are going to be a custom post type and the file attachments (downloads) are going to be added to each individual custom post type using custom fields. These custom fields are generated using the excellent Custom Metaboxes and Fields for WordPress.

This bit of information is important because by using Custom Metaboxes and Fields we are able to easily retrieve the attachment ID, which is what we really need to make this work. (see this example)

So, keep that in mind, the following can be used as long as you have that attachment ID.

Explanation: The above assumes that we’re in a loop of some sort and have already retrieved our attachment id, e.g. $file_id = get_post_meta( get_the_ID(), '_my_download_id', 1).

Then we use wp_get_attachment_url( $file_id ); to get the url for our attachment. We need this to generate the actual download link but we also want to save it as a variable so that we can use it in the wp_check_filetype( $file_url ) function. wp_check_filetype() returns an array of values containing the extension and mime type.

We then use the $filetype variable to output the extension with $filetype['ext'].

I might expand on this a bit more in the future to explain in detail how this was used but there should be enough there to be potentially useful.