怎么获取WordPress文章中上传的所有图片

追格官方小助手/ 2022年02月26日/ WordPress/ 浏览 1225

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);
    }
}?>


发表评论

暂无评论,抢个沙发...

客服 工单