The other day I got an interesting support thread for Easy Digital Downloads, asking for the list of files, and their sizes be displayed when viewing a product. Being that I only use it to sell WordPress plugins, it seemed pretty minor, but if you were dealing with larger Audio/Video files, or your consumers used their mobile devices frequently, I could see how this would be useful. So I put together a quick, single file, plugin that is now available in the EDD Library Repo on Github.

First, here’s the primary function that is run:

function edd_ck_show_file_sizes( $post_id ) {
	$files = edd_get_download_files( $post_id, null );
	$decimals = 2;
	$sz = 'BKMGTP';
	$header = _n( 'File Size', 'File Sizes', count( $files ), 'edd' );
	echo '<h5>' . $header . '</h5>';
	echo '<ul>';
	foreach( $files as $file ) {
		$bytes = filesize( get_attached_file( $file['attachment_id'] ) );
		$factor = floor((strlen($bytes) - 1) / 3);
		echo '<li>' . $file['name'] . ' - ' . sprintf( "%.{$decimals}f", $bytes / pow( 1024, $factor) ) . @$sz[$factor] . '</li>';
	echo '</ul>';
add_action( 'edd_after_download_content', 'edd_ck_show_file_sizes', 10, 1 );

Now, a quick overview. Basically what we’re doing is looking for all the uploaded media items attached as ‘Downloads’ to this product. Once we get them, we’re iterating through them. You see this in the line

$files = edd_get_download_files( $post_id, null );

After that we do some setup, only wanting 2 decimal places, setting up the title of the list (following the numeric localization method), and you’ll notice that odd variable BKMGTP. What is this? Well it’s used to make the output of the size calculation human readable. It’s for “Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, and Petabytes”. I’ve never seen a use case of someone selling Tera/Petabyte files on EDD, but who am I to judge.

After that, a little loop to run each calculation by powers of 1024, and we’re good to go!

You can go grab the full plugin-ready file here.

Image credit(CC): John Trainor

Posted by Chris Klosowski

Chris Klosowski is the President of Easy Digital Downloads, the easiest way to sell your digital products with WordPress. Trusted by over 50,000 smart store owners.