Get a File Size in Advanced Custom Fields

January 2, 2015

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:

{!{code class="language-php"}!}czoyNTU6XCImbHQ7P3BocA0KICAvLyBHZXQgdGhlIFwicG9kY2FzdF9maWxlXCIgZmllbGQgYW5kIG1ha2UgaXQgYSB2YXJpYWJsZQ0KIHtbJiomXX0gJGF0dGFjaG1lbnRfaWQgPSBnZXRfZmllbGQoXCdwb2RjYXN0X2ZpbGVcJyk7DQoNCiAgLy8gR2V0IHRoZSBhdHRhY2hlZCBmaWxlIGl7WyYqJl19biB0aGUgZmllbGQgYW5kIGRldGVybWluZSB0aGUgZmlsZSBzaXplDQogICRmaWxlc2l6ZSA9IGZpbGVzaXplKCBnZXRfYXR0YWNoZXtbJiomXX1kX2ZpbGUoICRhdHRhY2htZW50X2lkICkgKTsNCj8mZ3Q7XCI7e1smKiZdfQ=={!{/code}!}

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.

{!{code class="language-php"}!}czozODpcIiRmaWxlc2l6ZSA9IHNpemVfZm9ybWF0KCRmaWxlc2l6ZSwgMik7XCI7e1smKiZdfQ=={!{/code}!}

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:

{!{code class="language-php"}!}czozMDpcIiZsdDs/cGhwIGVjaG8gJGZpbGVzaXplOyA/Jmd0O1wiO3tbJiomXX0={!{/code}!}

Additional Resources