WordPress 获取文章的所有附件

原文来自:https://www.wpdaxue.com/get_attached_media.html

在 WordPress 项目开发中,也许我们需要获取某篇文章的附件,在 WordPress 3.6 以前的版本中,我们可以使用 get_children() 函数来获取,比如:

$args = array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'ASC',
);

$attachments = get_children( $args );

更多详情请阅读 get_children() 官方文档。

WordPress 3.6 新增了一个新函数 get_attached_media() ,让我们获取附件变得更加简单,比如:

获取所有类型的附件:

$attachments = get_attached_media( '', $post->ID );

获取图片附件:

$attachments = get_attached_media( 'image', $post->ID );

获取音频附件:

$attachments = get_attached_media( 'audio', $post->ID );

获取视频附件:

$attachments = get_attached_media( 'video', $post->ID );

更多详情,请阅读 get_attached_media() 官方文档