WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. Jole
    Member
    Posted 1 month 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.

    <?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:

    <?php
    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:

    <?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];
     }
    ?>

    Any help to combine it?

  2. vtxyzzy
    Member
    Posted 1 month 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.

Reply

You must log in to post.

About this Topic