I need to display some featured image info on post page. Among other info I need to display file size of image (featured image of post).
I tried this function inside single.php.
<?php
function getSize($file){
$bytes = filesize($file);
$s = array('b', 'Kb', 'Mb', 'Gb');
$e = floor(log($bytes)/log(1024));
return sprintf('%.2f '.$s[$e], ($bytes/pow(1024, floor($e))));
}
?>
and to echo that:
<?php echo getSize('/wp-content/uploads/2014/06/some-file-name.jpg'); ?>
It works, but I need help to make ti automatically grab featured image url, not to manually enter it in code?
For example I use this to echo featured image (“full”) url:
<?php
if ( has_post_thumbnail()) {
$full_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
echo $thumb_image_url[0];
}
?>
Could you please help to combine it, or to provide me with another solution?
1 Answer
You can use get_attached_file()
to:
Retrieve attached file path based on attachment ID.
And get_post_thumbnail_id()
to determine the post thumbnail of the current post, or any post if you set the $post_id
parameter. Exemplary usage:
$bytes = filesize(
get_attached_file(
get_post_thumbnail_id()
)
);
Use size_format()
to
Convert a given number of bytes into a human readable format
$hr_size = size_format( $bytes );
If you are actually want to get the size of one of the intermediate sizes, the above shows the file size of the full image, make use of image_get_intermediate_size()
, where:
The metadata ‘sizes’ is used for compatible sizes that can be used for the parameter $size value.
Which means it uses wp_get_attachment_metadata()
to get the data. In addition you need wp_upload_dir()
to construct the path. Exemplary usage:
$upload_dir = wp_upload_dir();
$metadata_size = image_get_intermediate_size(
get_post_thumbnail_id(),
'thumbnail'
);
$path_inter = $upload_dir[ 'basedir' ] . "https://wordpress.stackexchange.com/" . $metadata_size[ 'path' ];
$bytes = filesize(
$path_inter
);
$hr_size = size_format( $bytes );