Skip to content

Instantly share code, notes, and snippets.

@morgyface
Last active May 26, 2022 08:49
Show Gist options
  • Select an option

  • Save morgyface/725df3cb655db3f8de395b9db4fa80fc to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/725df3cb655db3f8de395b9db4fa80fc to your computer and use it in GitHub Desktop.
WordPress | File size from URL
<?php
// Return a neat file size
function nice_file_size($file_url, $precision = 2) {
$nice_file_size = null;
$attachment_id = attachment_url_to_postid($file_url); // Gets ID of file from URL
$file_path = get_attached_file( $attachment_id ); // Gets path using ID
if ( is_writable( $file_path ) ) { // Locally an error is thrown due to file not being writable
$size = filesize( $file_path ); // NB filesize only works with the path to the file NOT a URL
$base = log($size, 1024);
$suffixes = array('', 'KB', 'MB', 'GG', 'TB');
$nice_file_size = round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)];
}
return $nice_file_size;
}
?>
<?php
// Example
echo nice_file_size($download_url, 0);
?>
@morgyface
Copy link
Author

Updated May 2022

I discovered that, when working locally, files are typically unable to be accessed due to permissions. This causes filesize to print an error. I've therefore added a condition if ( is_writable( $file_path ) ) { which ensures the file is accessible before running filesize. Probably not a bad condition to have in place regardless of whether you're working locally or not.

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