Create Accessible Attachment Links

Posted on Thursday, December 4th, 2008 at 1:20 pm in

You can use the WordPress wp_get_attachment_link and get_attached_file functions in a number of ways to generate accessible download links — including outputting the file size and type.

The wp_get_attachment_link function has 4 parameters:

  1. the post ID
  2. the associated image size (‘thumbnail’ or ‘medium’)
  3. option to display the attachment’s permalink (boolean — ‘false’ or ‘true’)
  4. option to display an associated image icon (boolean — ‘false’ or ‘true’)

<?php
// create a text link to an attachment
$text_link = wp_get_attachment_link($post->ID,'',true,false);

// create a link to an attachment using an icon
$icon_link = wp_get_attachment_link($post->ID,'thumbnail',false,true);

// get an attachment filesize in kilobytes
$filesize = ceil(filesize(get_attached_file($post->ID))/1024).'K';

// grab an attachment extension
$bits = explode('.',get_attached_file($post->ID));
$ext = '.'.$bits[count($bits)-1].' format';

// put it all together
echo $icon_link. ' '.$text_link.' <small>('.$ext.' '.$filesize.')</small>';
?>

Example Output

Attachment Link Code

You might also be interested in

2 Comments

Add your comment

  1. Amith Nair - January 24, 2009 at 10:02 am

    I want to attach a document from my PC and i want that file to make it as a link, so that whenever i click on that link, i should open that particular attachmemnt…how to upload that attachment to make it as a link?/

    • Mel - January 26, 2009 at 12:31 pm

      Upload the file via the WordPress Add Media interface. Look for the starburst icon just above the post content entry area when adding/editing a post. From then on, it’s exactly like adding an image to a post.

Leave a Reply

WordPress Theme Development

Top