Last active
May 26, 2022 08:49
-
-
Save morgyface/725df3cb655db3f8de395b9db4fa80fc to your computer and use it in GitHub Desktop.
WordPress | File size from URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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); | |
| ?> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated May 2022
I discovered that, when working locally, files are typically unable to be accessed due to permissions. This causes
filesizeto print an error. I've therefore added a conditionif ( is_writable( $file_path ) ) {which ensures the file is accessible before runningfilesize. Probably not a bad condition to have in place regardless of whether you're working locally or not.