我正在使用以下模板代码显示附件链接:

$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()substr()wp_get_attachment_url())并打电话 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');

我会做 :

$attachment_filesize = filesize( get_attached_file( $attachment_id ) );

或具有可读的大小 423.82 KB

$attachment_filesize = size_format( filesize( get_attached_file( $attachment_id ) ), 2 );

参考: get_attached_file(), 文件大小(), size_format()

笔记 : 定义你的 $attachment_id

要查找通过自定义字段插件添加的文件的大小,我做到了:

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

只需确保将自定义字段的“返回值”设置为“文件对象”即可。

有一个更容易的解决方案,可以获取人类可读的文件大小。

$attachment_id  = $attachment->ID;
$attachment_meta = wp_prepare_attachment_for_js($attachment_id);

echo $attachment_meta['filesizeHumanReadable'];

我当时正在寻找相同的内容,并找到了这个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()

至少对于音频,文件大小保存为“元数据”。

$metadata = wp_get_attachment_metadata( $attachment_id );
echo $metadata['filesize'];

这个 不得 图像和视频是这种情况。

许可以下: CC-BY-SA归因
scroll top