Created
March 17, 2023 14:19
-
-
Save juanmafla/55857d8e05d890ba23a4fc3b1b9a9e8d to your computer and use it in GitHub Desktop.
Wordpress file size
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
| /* get width and height */ | |
| $file= wp_get_attachment_image_src( 1118, 'medium'); | |
| $image_width= $file[1]; | |
| $image_height= $file[2]; | |
| /*get file size */ | |
| $filemeta= wp_get_attachment_metadata(1118); //1118 is attachment ID | |
| $upload_dir= wp_upload_dir(); | |
| $filemeta_array = explode("/", $filemeta['file']); | |
| $baseurl= $upload_dir['basedir']; | |
| $year_upload = $filemeta_array[0]; | |
| $month_upload = $filemeta_array[1]; | |
| $filename= $filemeta['sizes']['medium']['file']; //change medium to your thumbnail size name | |
| $file_local_url= $baseurl.'/'.$year_upload.'/'.$month_upload.'/'.$filename; //it's because filesize() need relative path | |
| $attachment_filesize = filesize($file_local_url); | |
| echo $attachment_filesize; //print filesize in bytes. | |
| /* Function Converts bytes into human readable file size. */ | |
| function FileSizeConvert($bytes) { | |
| $bytes = floatval($bytes); | |
| $arBytes = array( | |
| 0 => array( | |
| "UNIT" => "TB", | |
| "VALUE" => pow(1024, 4) | |
| ), | |
| 1 => array( | |
| "UNIT" => "GB", | |
| "VALUE" => pow(1024, 3) | |
| ), | |
| 2 => array( | |
| "UNIT" => "MB", | |
| "VALUE" => pow(1024, 2) | |
| ), | |
| 3 => array( | |
| "UNIT" => "KB", | |
| "VALUE" => 1024 | |
| ), | |
| 4 => array( | |
| "UNIT" => "B", | |
| "VALUE" => 1 | |
| ), | |
| ); | |
| foreach($arBytes as $arItem) | |
| { | |
| if($bytes >= $arItem["VALUE"]) | |
| { | |
| $result = $bytes / $arItem["VALUE"]; | |
| $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"]; | |
| break; | |
| } | |
| } | |
| return $result; | |
| } | |
| echo FileSizeConvert($attachment_filesize); //print human readable file size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment