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); } }?>
还有一种是使用PHP的方法,在WordPress获取文章中第一张图片中有提到,但是这种纯php的方法是查找了文章中的所有图片,但并非上传的。什么意思?即外链的图片也会被计算其中。
参考资料:
https://developer.wordpress.org/reference/functions/get_posts/
https://wordpress.stackexchange.com/questions/22965/how-to-get-images-included-in-post