Skip to main content
Condensed code to use ternary operator
Source Link

Simple function to get attachment file size by attachment id, similar to another answer here but with a little error checking. AdditionalThere is also an additional parameter to specify the number of decimal points to return:

function tm_get_attachment_size($attachment_id, $decimals) {
    $file = get_attached_file( $attachment_id );
 
    if(return $file ) {
        $raw_file_size? =size_format( filesize( $file );
        $file_size = size_format($raw_file_size, $decimals);
        return $file_size;
    } else {
       ) return: 0;
    }
}

For example, say I have an attachment ID of 99: tm_get_attachment_size(99, 1) would return '1.4 MB'.

Simple function to get attachment file size by attachment id. Additional parameter to specify number of decimal points:

function tm_get_attachment_size($attachment_id, $decimals) {
    $file = get_attached_file( $attachment_id );
 
    if( $file ) {
        $raw_file_size = filesize( $file );
        $file_size = size_format($raw_file_size, $decimals);
        return $file_size;
    } else {
        return 0;
    }
}

For example, say I have an attachment ID of 99: tm_get_attachment_size(99, 1) would return '1.4 MB'.

Simple function to get attachment file size by attachment id, similar to another answer here but with a little error checking. There is also an additional parameter to specify the number of decimal points to return:

function tm_get_attachment_size($attachment_id, $decimals) {
    $file = get_attached_file( $attachment_id );
    return $file ? size_format( filesize($file), $decimals ) : 0;
}

For example, say I have an attachment ID of 99: tm_get_attachment_size(99, 1) would return '1.4 MB'.

Source Link

Simple function to get attachment file size by attachment id. Additional parameter to specify number of decimal points:

function tm_get_attachment_size($attachment_id, $decimals) {
    $file = get_attached_file( $attachment_id );

    if( $file ) {
        $raw_file_size = filesize( $file );
        $file_size = size_format($raw_file_size, $decimals);
        return $file_size;
    } else {
        return 0;
    }
}

For example, say I have an attachment ID of 99: tm_get_attachment_size(99, 1) would return '1.4 MB'.