Get a File Size in Advanced Custom Fields

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:

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:

Additional Resources

✏️ Handwritten by Geoff Graham on January 2, 2015

1 Comments

  1. marolo
    # April 12, 2018

    what if I want to add the file name (with extension too)

Comments are closed.