我使用以下模板代码显示附件链接:
$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()
和asubstr()
属于wp_get_attachment_url()
) 和电话filesize()
但这看起来很混乱,我只是想知道WordPress中是否有内置的方法。
最合适的回答,由SO网友:Joe Hoyle 整理而成
据我所知,WordPress没有内置任何功能,我只想:
filesize( get_attached_file( $attachment->ID ) );
SO网友:davemac
我以前在函数中使用过这个。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\');
SO网友:William Schroeder McKinley
要查找通过自定义字段插件添加的文件的大小,我执行了以下操作:
$fileObject = get_field( \'file \');
$fileSize = size_format( filesize( get_attached_file( $fileObject[\'id\'] ) ) );
只需确保将自定义字段的“返回值”设置为“文件对象”。
SO网友:Vayu
我也在寻找同样的解决方案,并找到了WordPress的内置解决方案。
$args = array(
\'post_type\' => \'attachment\',
\'numberposts\' => -1,
\'post_status\' => null,
\'post_parent\' => $main_post_id
);
$attachments = get_posts($args);
foreach ($attachments as $attachment)
{
$attachment_id = $attachment->ID;
$image_metadata = wp_get_attachment_metadata( $attachment_id );
the_attachment_link($attachment->ID, false);
echo the_attachment_link[\'width\'];
echo the_attachment_link[\'height\'];
}
更多信息,请访问
wp_get_attachment_metadata()
SO网友:Ravina
在wordpress中获取图像文件大小:
$query_images_args = array(
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'post_status\' => \'inherit\',
\'posts_per_page\' => 10,
);
$query_images = new WP_Query($query_images_args);
foreach ($query_images->posts as $image) {
$img_atts = wp_get_attachment_image_src($image->ID, $default);
$img = get_headers($img_atts[0], 1);
$size = $img["Content-Length"]/1024;
echo round($size);
}