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 Director of Technology at Sandhills Development, LLC, creators of fine WordPress plugins, and ecommerce solutions.

79 Comments

  1. […] EDD? Here’s a very handy snippet to show file sizes for downloads on the product pages. Sumobi also released a free extension for add-to-cart redirects on […]

    Reply

    1. This is a great suggestion, thanks!

      Reply

  2. Hi Chris, thanks for the code! I’ve added this to functions.php and then on my product page I’ve added;

    $post = get_post();
    edd_ck_show_file_sizes( $post->ID );

    which is almost working. Strangely, if I upload a file with the fes submission form it shows the size as 0.00, but if I upload a file from the WordPress dashboard it seems to show the size correctly. Any idea why this might be? Screenshot; https://i.imgur.com/E67VUal.png

    Thanks again.

    Tom

    Reply

    1. Hi, I am facing the same problem. As I found out, this is all from the fact that the plugin FES does not add parameter ‘attachment_id’ to the table ‘wp_postmeta’ in line ‘edd_download_files’.
      I found the file plugins/edd-fes/classes/fields/multiple_pricing.php
      and in the lines 513 and 523 added: ‘attachment_id’ => fes_get_attachment_id_from_url( $url, $user_id )
      And it all worked)
      But I don’t know if all this is right and there will be no problems in the future …) Thanks

      Reply

  3. hi, how to show
    file name with extension ?
    ex:
    name : test size : 39 kb type: zip

    tnx

    Reply

  4. There’s definately a great deal to know about this issue.
    I love all of the points you have made.

    Reply

  5. I’m really impressed together with your writing abilities and also with the structure in your weblog.
    Is that this a paid topic or did you customize it yourself?
    Anyway keep up the nice high quality writing, it’s rare to look a nice weblog like this one nowadays.

    my site; mpc-install.com

    Reply

  6. Today, I went to the beach front with my kids. I found a sea
    shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She
    placed the shell to her ear and screamed. There
    was a hermit crab inside and it pinched her ear. She never
    wants to go back! LoL I know this is entirely off topic but I had to tell
    someone!

    Reply

  7. Cytotec (Misoprostol) is used for reducing the risk of stomach ulcers in certain patients who take nonsteroidal anti-inflammatory drugs (NSAIDs).
    Buy Cytotec (Misoprostol) right now – https://artevinostudio.com/myphp/buyamoxilonline/ and save your money.
    Only 1.85$ Per pill!

    Reply

  8. That is really fascinating, You’re an overly skilled blogger.
    I have joined your rss feed and stay up for in the hunt for more of your fantastic post.
    Also, I have shared your web site in my social networks!

    My webpage … http://www.gazaldesign.xyz

    Reply

  9. Thanks for sharing your thoughts about code. Regards

    Reply

  10. Amoxicillin is a penicillin antibiotic. It kills or stops the growth of some bacteria. This medicine is used to treat many kinds of infections. It will not work for colds, flu, or other viral infections.
    Buy Amoxicillin right now – http://amoxicillina.weebly.com/ and save your money.
    Only 0.44 usd per pill!

    Reply

  11. Hoвoe oнлaйн Kaзuно – Бoнyc кaждoмy!
    Рeгистрирyйся – зaбери свoй Бoнyс и игрaй.
    нeoграничeный дeпoзит, и мoмeнтльный вывoд!
    https://cahopsong.tk/help/?15561621856649

    Reply

  12. viagra online ireland viagra online free shipping australia – wham 1180 viagra

    Reply

  13. prednisone in india buy prednisone – generic prednisone 10mg

    Reply

  14. amoxacillian without a percription order amoxil – cost of amoxicillin

    Reply

  15. The first 5G Verizon Innovative Learning Lab in a U.S. school is changing how students learn
    Breakthrough Schools and the 5G Verizon Innovative Learning Lab are taking ed-tech to the next level.

    Reply

  16. ivermectin 200mg ivermectin for humans – buy liquid ivermectin

    Reply

  17. where to buy ivermectin buy stromectol online – ivermectin where to buy

    Reply

  18. Synthroid is used for treating low thyroid hormone levels.
    https://wmdportal.com/tmb/buy-synthroid-online/ and save your money. Only highest quality and secure payments.
    Free delivery and free pills for every order.
    Only 0.21 usd per pill!

    Reply

  19. ivermectin otc ivermectin 12 mg tablets for sale – how much is ivermectin

    Reply

  20. ivermectin cream cost ivermectin pills for humans – stromectol coronavirus

    Reply

  21. pain meds online without doctor prescription prescription drugs online without doctor – male enhancement products

    Reply

  22. otc ed pills prescription drugs online without doctor – best drugs for erectile dysfunction

    Reply

  23. ed help cheap drugs online – erectial disfunction

    Reply

  24. ivermectin 1 topical cream purchase ivermectin – ivermectin generic

    Reply

  25. generic plaquenil pills plaquenil – cheap plaquenil

    Reply

  26. plaquenil cost for generic hydroxychloroquinegnr – plaquenil for sarcoidosis

    Reply

  27. ivermectin cream 5% buy stromectol – ivermectin 3mg pill

    Reply

  28. viagra 100mg price how much is viagra – 100mg viagra

    Reply

  29. I’ve been surfing on-line greater than 3 hours lately, yet I never discovered any
    fascinating article like yours. It’s lovely worth sufficient
    for me. In my opinion, if all website owners and bloggers made just right
    content as you did, the web shall be a lot more helpful than ever before.

    Reply

  30. buy real viagra online sildenafil – buying viagra online

    Reply

  31. best erectile dysfunction pills prescription drugs without doctor approval – best ed treatment

    Reply

  32. buy real viagra online viagra without a doctor prescription usa – 100mg viagra

    Reply

  33. dgeneric cialis best place to buy generic cialis online – canada pharmacy generic cialis

    Reply

  34. Hi there, i read your blog from time to time and i own a
    similar one and i was just curious if you get a lot of spam comments?
    If so how do you prevent it, any plugin or anything you can advise?

    I get so much lately it’s driving me crazy so any assistance is very much appreciated.

    Reply

  35. prednisone canada pharmacy prednisone oral – prednisone oral

    Reply

  36. Hi to all, how is all, I think every one is getting more from this website, and your views are fastidious in favor of new users.

    Reply

  37. Good answers in return of this query with solid arguments and explaining the whole thing about that.

    Reply

  38. order prednisone online canada buy prednisone – 5 prednisone in mexico

    Reply

  39. generic zithromax 500mg india zithromax – order zithromax without prescription

    Reply

  40. I am genuinely happy to glance at this website posts which consists of plenty of useful information,
    thanks for providing such statistics.

    Reply

  41. This is a really good tip especially to those fresh to the blogosphere.
    Brief but very precise information… Many thanks for sharing this one.

    A must read article!

    Reply

  42. Neurontin is used for treating seizures associated with epilepsy.
    Neurontin https://lifestrategies.ca/includes/cms/buyneurontinonline/ is an anticonvulsant.
    Use Neurontin as directed by your doctor.

    Reply

  43. stromectol liquid ivermectin for humans – ivermectin 5 mg price

    Reply

  44. Hey would you mind letting me know which web host you’re working with?
    I’ve loaded your blog in 3 different internet browsers and I must say this blog
    loads a lot quicker then most. Can you suggest a good web hosting provider at a honest price?
    Thanks, I appreciate it!

    Reply

  45. propecia purchase propecia buy without per – finasteride without prescription

    Reply

  46. Every weekend i used to pay a visit this site, for the reason that i want enjoyment, since this this web site conations actually
    fastidious funny stuff too.

    Reply

  47. Heya i am for the first time here. I found this board
    and I to find It truly useful & it helped me out a lot.
    I am hoping to provide something back and aid others such as you
    aided me.

    Reply

  48. Normally I don’t learn post on blogs, however I wish to say that this write-up very compelled me to try and do it!
    Your writing taste has been amazed me. Thanks,
    quite great article.

    Reply

  49. Для этой странице представлен ТОП самых лучших букмекерских контор России в 2021 году, которые работают легально на территории страны, имея весь необходимые лицензии и документы.

    интервью

    Круг беттор хочет овладевать через спектакль удовольствие, делать ставки на хорошие коэффициенты и гнездиться этом не робеть, сколько букмекерская контора может сообразно непонятным причинам отказать в выводе средств либо вконец заблокировать счёт. Следовательно неотлучно игроки ищут самого надёжного букмекера, с которым не будет подобных проблем. Несмотря для то, что разобщенный сайт, предлагающий заключать пари, имеет свои преимущества, некоторые всё же в большей мере выделяются над остальными. Именно таким БК стоит уделить уважение, ведь они не простой беспричинно занимают первые позиции в рейтинге. Одни букмекерские компании привлекают клиентов с путем высоких котировок, другие приятными бонусами и фрибетами, а третьи обширной линией онлнайн ставок в интернете и другими иными способами.

    Reply

  50. В конкурентной борьбе букмекеры привлекают клиентов различными бонусами и акциями, розыгрышами призов и ценных подарков. Следовательно ради сайте мы создали деление для бонусов. Здесь вы найдете актуальные собрание, которые помогут выбрать лучшую букмекерскую контору.

    Действительно, брать подарки навеки приятно. Преимущественно, когда они несут в себе практическую пользу. Предположим, новички в беттинге могут без траты собственных средств сделать одну либо несколько ставок. Такой бонус называется бездепозитный фрибет. Пропорционально сути, это виртуальные кусок, которые общество предоставляет пользователю для заключения пробного пари. Поскольку все неизвестно, понравится ли начинающему игроку битва и баста ли он одарять особенный счет, БК немого рискует, пусть и не реальными рублями. Не мочь, что такой бонус наедаться в арсенале далеко не у всех. Непременно, у компаний с бездепозитным фрибетом больше шансов войти в топ-5 букмекерских контор России.

    стало известно

    Отметим вторично скольконибудь типов вознаграждения от БК, которые операторы предоставляют подобно новичкам, так и действующим пользователям. Вот самые популярные упование бонусов:

    Фрибет – мочь соблюдать бесплатную ставку.
    Кэшбэк – возврат части средств с оборота сиречь только проигранных на пари.
    Страховка – компенсация части денег присутствие неудачной ставке.
    Неестественный коэффициент – способствовать следовательно пари с увеличенной котировкой.
    Букмекеры, фигурирующие ради вершине нашего рейтинга, нередко организуют ради клиентов специальные акции. Обычно проекты приурочены к резонансным спортивным матчам иначе знаменательным датам. Временами компании устраивают розыгрыши ценных призов пропорционально принципу лотереи сиречь с учетом активности игроков. Призами в таких мероприятиях могут быть даже автомобили класса премиум и квартиры.

    Reply

  51. buy cialis no prescription uk cialis no prescription canada – cialis no prescription overnight shipping

    Reply

  52. cialis online america cialis discounts – cialis mail order

    Reply

  53. Букмекерская контора (БК) — игорное правило, принимающее ставки в основном для спортивные соревнования. Аналитики БК оценивают вероятность события и определяют его коэффициент: буде ставка игрока выигрывает, ее скопление умножается на выставленный коэффициент, получившаяся сложность и является выигрышем. Коли предугадать капут события не удалось, ставка проигрывает, и деньги достаются букмекерской конторе. Безотлагательно легальные букмекеры РФ работают или офлайн, в формате пунктов приёма ставок (ППС), спроста и онлайн в интернете.

    Адреса ППС в каждом крупном городе России дозволено найти у нас, в разделе Букмекерские клубы (ППС). В пунктах приема ставок осуществляется наличный плата, а выплата выигрышей производится через кассу.

    подробности

    Впрочем теперь набирают имя букмекерские конторы онлайн. Слушаться ставку онлайн дозволительно либо для легальном сайте букмекерской конторы, либо в мобильном приложении. Чем удобнее сайт либо мобильное прибавление, тем больше шансов у букмекера привлечь новых клиентов.

    Reply

  54. amoxicillin without a doctor’s prescription trusted india online pharmacies – how can i order prescription drugs without a doctor

    Reply

  55. cialis buy without cialis buy cheap with master card – cialis super active plus

    Reply

  56. brand cialis 20mg cialis discounts – free cialis medication

    Reply

  57. drug medication best canadian mail order pharmacies – causes for ed

    Reply

  58. I am really thankful to the owner of this web page who has shared this great paragraph at at this place.

    quest bars http://j.mp/3jZgEA2 quest bars

    Reply

  59. Can I just say what a relief to discover somebody who truly
    knows what they are discussing over the internet.
    You actually realize how to bring an issue to light and
    make it important. A lot more people need to read this and understand
    this side of the story. I was surprised you’re not
    more popular given that you surely have the gift. asmr
    https://app.gumroad.com/asmr2021/p/best-asmr-online asmr

    Reply

  60. generic viagra walmart viagra pills – viagra from india

    Reply

  61. erectial disfunction weight loss pills from canada – male dysfunction pills

    Reply

  62. cost of ivermectin 1% cream ivermectin – ivermectin 3mg pill

    Reply

  63. ivermectin pills human ivermectin – ivermectin

    Reply

  64. What’s up, the whole thing is going sound here and ofcourse every one is sharing data, that’s
    actually fine, keep up writing. quest bars https://www.iherb.com/search?kw=quest%20bars quest bars

    Reply

  65. With havin so much written content do you ever run into any issues of plagorism or copyright violation? My blog
    has a lot of exclusive content I’ve either created myself or outsourced but it appears a lot of it is popping it
    up all over the internet without my agreement. Do you know any techniques to
    help reduce content from being ripped off? I’d truly appreciate it.

    cheap flights http://1704milesapart.tumblr.com/ cheap flights

    Reply

  66. Very nice post. I simply stumbled upon your weblog and wished to say
    that I have truly loved browsing your weblog posts.
    In any case I will be subscribing on your rss feed and
    I hope you write again very soon! scoliosis surgery
    https://0401mm.tumblr.com/ scoliosis surgery

    Reply

  67. I do not even know how I finished up here, but I believed this
    submit used to be great. I don’t recognise who you are but definitely
    you’re going to a famous blogger in the event you aren’t already.

    Cheers! scoliosis surgery https://coub.com/stories/962966-scoliosis-surgery scoliosis surgery

    Reply

  68. ivermectin pills human buy ivermectin online – ivermectin 1 topical cream

    Reply

  69. ivermectin cost ivermectin cost – buy ivermectin

    Reply

Leave a reply

Your email address will not be published. Required fields are marked *