Properly Format your Filesize in WordPress
When you display attachments within a post/page and want to show the attachments’ sizes next to their filenames, you would probably do something like this:
- // size calculation
- $docsize = @filesize($file_path);
- // show the attachment
- echo $filename . ' — ' . $docsize;
// size calculation $docsize = @filesize($file_path); // show the attachment echo $filename . ' — ' . $docsize;
and the output would be something like this:
attachment.zip — 13143
Looking nice but you can make it even nicer if you format the $docsize variable, i.e. show the size unit next to it (e.g. kB, MB, etc.) WordPress fortunately has a built-in function that allows you to format file sizes easily. The magic function is size_format(), located in wp-includes/functions.php:
- function size_format( $bytes, $decimals = 0 ) {
- $quant = array(
- // ========================= Origin ====
- 'TB' => 1099511627776, // pow( 1024, 4)
- 'GB' => 1073741824, // pow( 1024, 3)
- 'MB' => 1048576, // pow( 1024, 2)
- 'kB' => 1024, // pow( 1024, 1)
- 'B ' => 1, // pow( 1024, 0)
- );
- foreach ( $quant as $unit => $mag )
- if ( doubleval($bytes) >= $mag )
- return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
- return false;
- }
function size_format( $bytes, $decimals = 0 ) {
$quant = array(
// ========================= Origin ====
'TB' => 1099511627776, // pow( 1024, 4)
'GB' => 1073741824, // pow( 1024, 3)
'MB' => 1048576, // pow( 1024, 2)
'kB' => 1024, // pow( 1024, 1)
'B ' => 1, // pow( 1024, 0)
);
foreach ( $quant as $unit => $mag )
if ( doubleval($bytes) >= $mag )
return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
return false;
}Now when you output your attachments, use this instead:
- // size calculation
- $docsize = @filesize($file_path);
- if (FALSE === $docsize)
- $docsize = 0;
- else
- $docsize = size_format($docsize);
- // show the attachment
- echo $filename . ' — ' . $docsize;
// size calculation $docsize = @filesize($file_path); if (FALSE === $docsize) $docsize = 0; else $docsize = size_format($docsize); // show the attachment echo $filename . ' — ' . $docsize;
and your output will be:
attachment.zip — 13 kB
Looking better now, right? What about the decimal? Just change line 6 of the above snippet to this:
- $docsize = size_format($docsize, 2);
$docsize = size_format($docsize, 2);
The number we have just added will determine how many numbers will appear after the dot. If you change that number to 3, your output will now be:
attachment.zip — 12.835 kB
Sweet, eh?









Recent Opinions