Get the size (size in Kb or MB) of an featured image?

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 );

Leave a Comment