1

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?

7

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' ] . '/' . $metadata_size[ 'path' ];
$bytes = filesize(
    $path_inter
);
$hr_size = size_format( $bytes );
  • I am new to WP. Could you please paste for me exactly what I should put inside single.php to show file size of featured image? For, at least 'full" image size, "medum" image size would be great too? – Advanced SEO Jun 30 '14 at 14:53
  • 1
    @user1038179 All you need is outlined in my answer. You really pretty much just have to use it, read the documentation I linked for each functionality. The last code block should definitely get you there. Good luck! – Nicolai Jun 30 '14 at 16:34
  • Thanks. Still, it is difficult for me to understand which of php codes, with or without any modification, in which order to paste in my single.php? I tried many times, but, I get nothing. – Advanced SEO Jul 1 '14 at 6:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.