如何显示WordPress文章中的所有图片(含媒体库图片)
解决WordPress文章图片全量获取问题
你当前的代码是通过post_parent关联来获取图片的——只有直接在文章编辑页上传的图片会自动把post_parent设为当前文章ID,而从媒体库选择的图片如果原本属于其他文章、或未关联任何文章,post_parent就不是当前文章ID,所以拿不到。
要获取文章里的所有图片,推荐用「提取文章内容中的图片URL,再匹配对应附件ID」的方法,具体代码如下:
// 获取当前文章内容 $post_content = get_post_field('post_content', $post->ID); // 正则匹配内容里的所有img标签src属性 preg_match_all('/<img[^>]+src="([^">]+)"/i', $post_content, $matches); // 去重,避免重复显示同一张图片 $unique_img_urls = array_unique($matches[1]); foreach ($unique_img_urls as $img_url) { // 通过图片URL获取对应的附件ID $att_id = attachment_url_to_postid($img_url); // 确保是有效的图片附件后再输出 if ($att_id && wp_attachment_is_image($att_id)) { echo wp_get_attachment_image($att_id, 'full'); } }
补充优化:同时保留关联图片
如果需要同时覆盖「已关联文章但未插入内容的图片」和「插入内容的所有图片」,可以把两种来源的图片ID合并后去重:
// 原方法获取关联到当前文章的图片 $attachments = get_children(array( 'post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' )); // 提取文章内容里的图片ID $post_content = get_post_field('post_content', $post->ID); preg_match_all('/<img[^>]+src="([^">]+)"/i', $post_content, $matches); $unique_img_urls = array_unique($matches[1]); $content_att_ids = array(); foreach ($unique_img_urls as $img_url) { $att_id = attachment_url_to_postid($img_url); if ($att_id && wp_attachment_is_image($att_id)) { $content_att_ids[] = $att_id; } } // 合并两个来源的ID并去重 $all_att_ids = array_unique(array_merge(array_keys($attachments), $content_att_ids)); // 输出所有图片 foreach ($all_att_ids as $att_id) { echo wp_get_attachment_image($att_id, 'full'); }
内容的提问来源于stack exchange,提问作者Sayed Newaz
相关产品推荐
相关产品推荐

