問題描述

我使用以下模板程式碼來顯示附件連結:

$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => $main_post_id
);

$attachments = get_posts($args);

foreach ($attachments as $attachment)
{
    the_attachment_link($attachment->ID, false);
}

但連結後,我需要顯示檔案的大小。我該怎麼做?

我猜想我可以確定檔案的路徑 (透過 wp_upload_dir()wp_get_attachment_url()substr()),並呼叫 filesize(),但這似乎凌亂,我只是想知道是否有一種方法內建到 WordPress 。

最佳解決方案

據我所知,WordPress 沒有內建這個,我只會做:

 filesize( get_attached_file( $attachment->ID ) );

次佳解決方案

我以前在 functions.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))));}

然後在我的模板中:

echo getSize('insert reference to file here');

第三種解決方案

要找到透過自定義欄位外掛新增的檔案的大小,我做到了:

$fileObject = get_field( 'file ');
$fileSize   = size_format( filesize( get_attached_file( $fileObject['id'] ) ) );

只需確保將自定義欄位的”Return Value” 設定為”File Object” 。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。