获取WordPress文章中上传的所有图片实现方法

发布时间:

WordPress的图片如果是在发布、编辑时上传的,那么是有一个隶属于关系,即:图片是隶属于这一篇文章。我们可以通过这种隶属关系将文章中的所有图片找出来。

在single.php页面的the_loop代码片段中加入:

<?php 
$args = array( 
  'post_type' => 'attachment', // 属于附件类型
  'numberposts' => -1, // 查出所有内容
  'post_status' => null, // 发布状态
  'post_mime_type' => 'image', // 附件类型为图片
  'post_parent' => $post->ID // 隶属于这篇文章
); 
$attachments = get_posts( $args );
// 如果存在
if ( $attachments ) {
    // 循环输出
    foreach ( $attachments as $attachment ) {
        var_dump($attachment);
    }
}?>

下图就是循环输出文章中的图片截图:

获取WordPress文章中上传的所有图片实现方法
还有一种是使用PHP的方法,在WordPress获取文章中第一张图片中有提到,但是这种纯php的方法是查找了文章中的所有图片,但并非上传的。什么意思?即外链的图片也会被计算其中。