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
<a href="http://codex.wordpress.org/Function_Reference/size_format">size_format()</a> 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.
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: