如何获取WordPress文章中上传的所有图片?

本文介绍了获取WordPress文章图片的实用方法。推荐使用内置函数:一是通过正则表达式从文章内容提取图片URL;二是获取文章附件及特色图片的详细信息。还提供了综合获取函数,可完整提取所有相关图片数据,便于开发者灵活调用。

文章作者:
阅读时间: 65 分钟
更新时间:2026年4月15日

获取 WordPress 文章中上传的所有图片有多种方法,这里提供最实用的几种方案:

一、使用内置 WordPress 函数(推荐)

1. 从文章内容中提取图片

function get_post_images($post_id = null) {
    if (!$post_id) {
        global $post;
        $post_id = $post->ID;
    }
    
    $post_content = get_post_field('post_content', $post_id);
    $images = array();
    
    // 方法1:使用正则表达式匹配所有图片
    preg_match_all('/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i', $post_content, $matches);
    
    if (!empty($matches[1])) {
        $images = array_unique($matches[1]); // 去重
    }
    
    // 方法2:匹配各种图片标签(包括 srcset)
    preg_match_all('/(?:src|srcset)=["\']([^"\']+)["\']/i', $post_content, $all_sources);
    
    if (!empty($all_sources[1])) {
        $all_images = array_unique($all_sources[1]);
        $images = array_merge($images, $all_images);
    }
    
    return array_unique($images);
}

// 使用示例
$post_images = get_post_images(123); // 获取指定文章ID的图片
// 或
$post_images = get_post_images(); // 获取当前文章的图片

2. 获取文章附件(包括特色图片)

function get_post_attachments($post_id = null) {
    if (!$post_id) {
        global $post;
        $post_id = $post->ID;
    }
    
    $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);
    $images = array();
    
    foreach ($attachments as $attachment) {
        $image_data = wp_get_attachment_image_src($attachment->ID, 'full');
        if ($image_data) {
            $images[] = array(
                'id'    => $attachment->ID,
                'url'   => $image_data[0],
                'width' => $image_data[1],
                'height'=> $image_data[2],
                'alt'   => get_post_meta($attachment->ID, '_wp_attachment_image_alt', true),
                'title' => $attachment->post_title,
                'caption' => $attachment->post_excerpt
            );
        }
    }
    
    // 包含特色图片
    if (has_post_thumbnail($post_id)) {
        $thumbnail_id = get_post_thumbnail_id($post_id);
        $thumb_data = wp_get_attachment_image_src($thumbnail_id, 'full');
        
        $images[] = array(
            'id'    => $thumbnail_id,
            'url'   => $thumb_data[0],
            'width' => $thumb_data[1],
            'height'=> $thumb_data[2],
            'alt'   => get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true),
            'title' => get_the_title($thumbnail_id),
            'featured' => true
        );
    }
    
    return $images;
}

二、综合获取函数(最完整)

function get_all_post_images($post_id = null, $include_featured = true) {
    if (!$post_id) {
        global $post;
        $post_id = $post->ID;
    }
    
    $all_images = array();
    
    // 1. 获取文章内容中的图片
    $post_content = get_post_field('post_content', $post_id);
    
    // 匹配所有图片标签
    preg_match_all('/<img[^>]+>/i', $post_content, $img_tags);
    
    foreach ($img_tags[0] as $img_tag) {
        // 提取 src
        preg_match('/src=["\']([^"\']+)["\']/i', $img_tag, $src_match);
        if (empty($src_match[1])) continue;
        
        $img_url = $src_match[1];
        
        // 提取 alt
        preg_match('/alt=["\']([^"\']*)["\']/i', $img_tag, $alt_match);
        $img_alt = $alt_match[1] ?? '';
        
        // 提取 class
        preg_match('/class=["\']([^"\']+)["\']/i', $img_tag, $class_match);
        $img_class = $class_match[1] ?? '';
        
        // 尝试获取附件 ID
        $attachment_id = 0;
        if (preg_match('/wp-image-(\d+)/i', $img_class, $id_match)) {
            $attachment_id = intval($id_match[1]);
        } else {
            // 通过图片 URL 查找附件
            $attachment_id = attachment_url_to_postid($img_url);
        }
        
        $image_data = array(
            'url' => $img_url,
            'alt' => $img_alt,
            'attachment_id' => $attachment_id
        );
        
        // 如果找到附件 ID,获取更多信息
        if ($attachment_id) {
            $attachment = wp_get_attachment_image_src($attachment_id, 'full');
            if ($attachment) {
                $image_data['full_url'] = $attachment[0];
                $image_data['width'] = $attachment[1];
                $image_data['height'] = $attachment[2];
                $image_data['caption'] = wp_get_attachment_caption($attachment_id);
            }
        }
        
        $all_images[$img_url] = $image_data;
    }
    
    // 2. 获取文章附件
    $args = array(
        'post_parent'    => $post_id,
        'post_type'      => 'attachment',
        'post_mime_type' => 'image',
        'posts_per_page' => -1
    );
    
    $attachments = get_posts($args);
    
    foreach ($attachments as $attachment) {
        $img_url = wp_get_attachment_url($attachment->ID);
        
        if (!isset($all_images[$img_url])) {
            $all_images[$img_url] = array(
                'url' => $img_url,
                'alt' => get_post_meta($attachment->ID, '_wp_attachment_image_alt', true),
                'attachment_id' => $attachment->ID,
                'full_url' => $img_url,
                'width' => '',
                'height' => '',
                'caption' => $attachment->post_excerpt,
                'title' => $attachment->post_title
            );
        }
    }
    
    // 3. 包含特色图片
    if ($include_featured && has_post_thumbnail($post_id)) {
        $thumbnail_id = get_post_thumbnail_id($post_id);
        $thumb_url = wp_get_attachment_url($thumbnail_id);
        
        if (!isset($all_images[$thumb_url])) {
            $thumb_data = wp_get_attachment_image_src($thumbnail_id, 'full');
            
            $all_images[$thumb_url] = array(
                'url' => $thumb_url,
                'alt' => get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true),
                'attachment_id' => $thumbnail_id,
                'full_url' => $thumb_data[0],
                'width' => $thumb_data[1],
                'height' => $thumb_data[2],
                'caption' => wp_get_attachment_caption($thumbnail_id),
                'title' => get_the_title($thumbnail_id),
                'featured' => true
            );
        } else {
            $all_images[$thumb_url]['featured'] = true;
        }
    }
    
    return array_values($all_images);
}

三、短代码实现(方便在编辑器中调用)

// 注册短代码
add_shortcode('post_images', 'display_post_images_shortcode');

function display_post_images_shortcode($atts) {
    $atts = shortcode_atts(array(
        'post_id' => null,
        'size'    => 'thumbnail',
        'columns' => 3,
        'link'    => 'file' // 'file', 'post', 'none'
    ), $atts);
    
    $post_id = $atts['post_id'] ?: get_the_ID();
    $images = get_all_post_images($post_id);
    
    if (empty($images)) {
        return '<p>本文暂无图片</p>';
    }
    
    $output = '<div class="post-images-gallery columns-' . esc_attr($atts['columns']) . '">';
    
    foreach ($images as $image) {
        $img_url = $image['full_url'] ?? $image['url'];
        $thumb_url = $image['url'];
        
        if (isset($image['attachment_id']) && $image['attachment_id']) {
            $thumb = wp_get_attachment_image($image['attachment_id'], $atts['size']);
        } else {
            $thumb = '<img src="' . esc_url($thumb_url) . '" alt="' . esc_attr($image['alt']) . '">';
        }
        
        $output .= '<div class="gallery-item">';
        
        if ($atts['link'] === 'file') {
            $output .= '<a href="' . esc_url($img_url) . '" class="lightbox" data-lightbox="post-gallery">';
            $output .= $thumb;
            $output .= '</a>';
        } elseif ($atts['link'] === 'post' && isset($image['attachment_id'])) {
            $output .= '<a href="' . get_attachment_link($image['attachment_id']) . '">';
            $output .= $thumb;
            $output .= '</a>';
        } else {
            $output .= $thumb;
        }
        
        if (!empty($image['caption'])) {
            $output .= '<p class="caption">' . esc_html($image['caption']) . '</p>';
        }
        
        $output .= '</div>';
    }
    
    $output .= '</div>';
    
    // 添加 CSS
    $output .= '<style>
        .post-images-gallery {
            display: grid;
            gap: 15px;
            margin: 20px 0;
        }
        .post-images-gallery.columns-1 { grid-template-columns: 1fr; }
        .post-images-gallery.columns-2 { grid-template-columns: repeat(2, 1fr); }
        .post-images-gallery.columns-3 { grid-template-columns: repeat(3, 1fr); }
        .post-images-gallery.columns-4 { grid-template-columns: repeat(4, 1fr); }
        .gallery-item img { width: 100%; height: auto; }
    </style>';
    
    return $output;
}

四、在模板文件中使用

1. 显示文章所有图片

<?php
// 在 single.php 或 content.php 中使用
$images = get_all_post_images();

if ($images) : ?>
    <div class="article-images">
        <h3>本文图片 (<?php echo count($images); ?> 张)</h3>
        <div class="image-grid">
            <?php foreach ($images as $image) : ?>
                <div class="image-item">
                    <img src="<?php echo esc_url($image['url']); ?>" 
                         alt="<?php echo esc_attr($image['alt']); ?>"
                         loading="lazy">
                    <?php if (!empty($image['caption'])) : ?>
                        <p class="image-caption"><?php echo esc_html($image['caption']); ?></p>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
<?php endif; ?>

2. 获取并导出图片信息

<?php
// 获取所有图片并保存为 JSON
$post_images = get_all_post_images();

if ($post_images) {
    $images_data = array();
    
    foreach ($post_images as $image) {
        $images_data[] = array(
            'original_url' => $image['url'],
            'full_size' => $image['full_url'] ?? $image['url'],
            'description' => $image['caption'] ?? '',
            'alt_text' => $image['alt'] ?? '',
            'is_featured' => !empty($image['featured'])
        );
    }
    
    // 保存为 JSON 文件
    $upload_dir = wp_upload_dir();
    $json_file = $upload_dir['basedir'] . '/post-' . get_the_ID() . '-images.json';
    file_put_contents($json_file, json_encode($images_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}
?>

五、高级功能:获取所有文章中所有图片

function get_all_site_images($limit = 100) {
    global $wpdb;
    
    $images = array();
    
    // 方法1:从文章内容中提取
    $posts = get_posts(array(
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => $limit,
        'fields'         => 'ids'
    ));
    
    foreach ($posts as $post_id) {
        $post_images = get_all_post_images($post_id);
        $images = array_merge($images, $post_images);
    }
    
    // 方法2:从媒体库查询
    $attachments = get_posts(array(
        'post_type'      => 'attachment',
        'post_mime_type' => 'image',
        'posts_per_page' => $limit,
        'post_status'    => 'inherit'
    ));
    
    foreach ($attachments as $attachment) {
        $img_url = wp_get_attachment_url($attachment->ID);
        
        $images[$img_url] = array(
            'url'           => $img_url,
            'attachment_id' => $attachment->ID,
            'alt'           => get_post_meta($attachment->ID, '_wp_attachment_image_alt', true),
            'caption'       => $attachment->post_excerpt,
            'title'         => $attachment->post_title,
            'uploaded_date' => $attachment->post_date
        );
    }
    
    return array_values(array_unique($images, SORT_REGULAR));
}

六、实用小贴士

1. 添加到 functions.php

将上述函数添加到主题的 functions.php文件中。

2. 使用方法

// 获取当前文章的所有图片
$images = get_all_post_images();

// 获取指定文章的所有图片
$images = get_all_post_images(123);

// 在前端显示
print_r($images);

// 使用短代码

[post_images]

[post_images post_id=”123″ columns=”4″ size=”medium”]

3. 性能优化

对于大量图片,考虑缓存结果:

function get_cached_post_images($post_id) {
    $cache_key = 'post_images_' . $post_id;
    $images = wp_cache_get($cache_key, 'posts');
    
    if (false === $images) {
        $images = get_all_post_images($post_id);
        wp_cache_set($cache_key, $images, 'posts', 3600); // 缓存1小时
    }
    
    return $images;
}

七、注意事项

  1. 相对路径处理:如果图片使用相对路径,使用 wp_make_link_absolute()转换
  2. 外部图片:函数也会获取外部链接的图片
  3. 性能考虑:文章图片过多时,考虑分页加载
  4. 安全性:输出时始终使用 esc_url()esc_attr()

这个方案可以获取文章中的所有图片,包括特色图片、内容中的图片、以及通过媒体库上传的附件图片。

这篇文章有用吗?

点击星号为它评分!

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

在AI工具中继续讨论:
曾凤祥
曾凤祥
WordPress技术负责人
WordPress 独立站开发领域 10+ 年实践经验,长期专注于外贸独立站搭建与 SEO 优化,累计服务企业客户数百家(含制造业、外贸企业、政府等行业)
相关文章
无论你是否已有网站,我们都能帮你把线上业务推上新高度
无论什么行业,都能快速拥有专业网站:
无论什么行业,都能快速拥有专业网站:

展示型官网 / 品牌站 / 外贸独立站,均有成熟模板与定制方案
无需懂代码:可视化编辑+我们指导,轻松启动 → 快速上线,抢占先机​
结构清晰、利于SEO与后期运营,降低长期维护成本

立即查看建站方案
网站加载慢、跳出高、询盘少?
网站加载慢、跳出高、询盘少?

老旧体验与技术隐患会直接拖累获客与转化。
我们提供:网站全面诊断 → 速度/安全/结构优化 → 可持续运维支持(技术+策略),让网站真正成为您的业务增长工具,而不只是“线上门面”。

马上获取专属优化方案
微信联系
chat 扫码联系
模板建站
挑选模板
网站定制
免费诊断
咨询热线
咨询热线

189-0733-7671

返回顶部