I use the Advanced Custom Fields plugin on nearly every WordPress project I work on. It’s so slick in extending the WordPress editor to add any number of custom fields and is so easy to implement, that I really hope it gets baked into native WordPress at some point in time.

I ran into a situation where I needed to detect the size of a file uploaded to a custom field and display that file size on the page. For example, I had created a File field in ACF and was using it to upload MP3 files. I wanted to be able to grab the size of that uploaded file (e.g. 3 MB) and display it on a page.

This stumped me, but it turned out to be a lot more straightforward than I expected.

Step 1: Set up the Custom Field

Duh, right? I mean, we do need to set up a custom field in order for this to work properly.

For this example, we’re creating a File field called “podcast_file.” Note that the Return Value is set to “File ID.” It’s that second part that hung me out to dry.

Step 2: Define the File Variables

Next up, we need to do two things:

  • Grab the uploaded file as an object
  • Detect the size of that object

Adding this snippet to our template does exactly that:

  // Get the "podcast_file" field and make it a variable
  $attachment_id = get_field('podcast_file');

  // Get the attached file in the field and determine the file size
  $filesize = filesize( get_attached_file( $attachment_id ) );

Presto! This gives us a new variable called $filesize that we can use to output the size of our attached file.

Bonus: The above will spit the file size out in bytes. However, we can use the WordPress size_format() function to format the file size into kilobytes. For example, add this to the end of the snippet to format the file size in kilobytes, rounded to two decimal points.

$filesize = size_format($filesize, 2);

Step 3: Output the File Size

Now that we’ve created a variable that detects (and possibly formats) the file size, you can echoit in your template as you would any other variable:

<?php echo $filesize; ?>

Additional Resources


Subscribe to Devigner Digest

I read a lot of crap about design and development and 90% really is crap. Subscribe and I will send links to the other 10% about once a month.