Skip to content

Instantly share code, notes, and snippets.

@morgyface
Created May 10, 2018 18:02
Show Gist options
  • Select an option

  • Save morgyface/7f4628dc86f87c059fe345bda4b3f143 to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/7f4628dc86f87c059fe345bda4b3f143 to your computer and use it in GitHub Desktop.
WordPress | File size and extension
<?php
$download_file = get_sub_field('download_file');
$download_url = $download_file['url'];
$download_path = pathinfo($download_url);
$download_ext = $download_path['extension'];
$download_size = filesize( get_attached_file( $download_file['id'] ) );
function format_bytes($size, $precision = 2) {
$base = log($size, 1024);
$suffixes = array('', 'KB', 'MB', 'GG', 'TB');
return round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)];
}
$download_size = format_bytes($download_size);
?>
@morgyface
Copy link
Author

Getting the file extension and file size of an uploaded file

Pretty self explanatory really. Uses PHP's filesize (more info here) though it returns bytes, the format_bytes function converts those bytes into a sensible format.

Stick the function in your theme's functions.php and use where you see fit.

Could be broken up into a number of functions to de-verbose. I'll leave that to you.

@morgyface
Copy link
Author

A more specific, versatile and recent file size function is available here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment