How do I get the size (file size in Kb or MB) of an featured image in post? (2 posts)

  1. Advanced SEO
    Posted 2 years ago #

    I need to display some featured image info on post page. One of those data I need to display is file size of image (featured image of post).

    I tried this function inside single.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 than to echo that size with:

    echo getSize('/wp-content/uploads/2014/06/image-file-name.jpg');

    And it works fine, but what I need is help to make ti automatically grab featured image url, not to manually enter it?

    For example I use this to echo featured image ("full") url:

     if ( has_post_thumbnail()) {
       $full_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
    echo $thumb_image_url[0];

    Any help to combine it?

  2. vtxyzzy
    Posted 2 years ago #

    wp_get_attachment_image_src() returns the height and width of the image in the return array. See this Codex article: http://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src

    EDIT: Sorry those are pixel values, but can you use the returned ID with get_posts() and an post_type of 'attachment'. Use the 'guid' field for the parameter to your getSize() function.

Topic Closed

This topic has been closed to new replies.

About this Topic