問題描述
我使用以下模板代碼來顯示附件鏈接:
$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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。