Question

I'm using the following template code to display attachment links:

$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => $main_post_id
);

$attachments = get_posts($args);

foreach ($attachments as $attachment)
{
    the_attachment_link($attachment->ID, false);
}

but after the link I need to display the file's size. How can I do this?

I'm guessing I could determine the file's path (via wp_upload_dir() and a substr() of wp_get_attachment_url()) and call filesize() but that seems messy, and I'm just wondering if there's a method built into WordPress.

Was it helpful?

Solution

As far as I know, WordPress has nothing built in for this, I would just do:

filesize( get_attached_file( $attachment->ID ) );

OTHER TIPS

I have used this before in functions.php to display the file size in an easily readable format:

function getSize($file){
$bytes = filesize($file);
$s = array('b', 'Kb', 'Mb', 'Gb');
$e = floor(log($bytes)/log(1024));
return sprintf('%.2f '.$s[$e], ($bytes/pow(1024, floor($e))));}

And then in my template:

echo getSize('insert reference to file here');

I would do :

$attachment_filesize = filesize( get_attached_file( $attachment_id ) );

Or with readable size like 423.82 KB

$attachment_filesize = size_format( filesize( get_attached_file( $attachment_id ) ), 2 );

Refs : get_attached_file(), filesize(), size_format()

Note : Define your $attachment_id

To find the size of a file added through the custom fields plugin, I did this:

$fileObject = get_field( 'file ');
$fileSize   = size_format( filesize( get_attached_file( $fileObject['id'] ) ) );

Just make sure you set the custom field's "Return Value" to "File Object".

There's an easier solution, to get human readable file sizes.

$attachment_id  = $attachment->ID;
$attachment_meta = wp_prepare_attachment_for_js($attachment_id);

echo $attachment_meta['filesizeHumanReadable'];

I was looking for the same and found this WordPress built-in solution.

$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => $main_post_id
);

$attachments = get_posts($args);

foreach ($attachments as $attachment)
{
    $attachment_id = $attachment->ID;
    $image_metadata = wp_get_attachment_metadata( $attachment_id );
    the_attachment_link($attachment->ID, false);
    echo the_attachment_link['width'];
    echo the_attachment_link['height'];
}

See more at wp_get_attachment_metadata()

For audio at least, the file size is saved as "metadata".

$metadata = wp_get_attachment_metadata( $attachment_id );
echo $metadata['filesize'];

This may not be the case for images and video.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top