如何获取WordPress站点文章与页面所用图片列表以清理未使用图片
获取WordPress站点中被使用的图片URL列表
方法一:改进SQL查询提取图片URL
MySQL 8.0+版本适用
直接用REGEXP_SUBSTR函数提取内容里的图片URL,去重后输出:
SELECT DISTINCT REGEXP_SUBSTR(post_content, 'https?://example\\.com/wp-content/uploads/[^"\'<>]+') AS used_image_url FROM wp_posts WHERE post_type IN ('post', 'page') AND post_status = 'publish' AND post_content REGEXP 'https?://example\\.com/wp-content/uploads/[^"\'<>]+';
- 把
example\\.com换成你的实际域名(注意点号要转义) DISTINCT用来避免同一图片重复出现- 只查已发布的文章和页面,排除草稿、回收站等状态的内容
MySQL 5.x版本适用
5.x不支持REGEXP_SUBSTR,用函数提取只能拿到单篇内容里的第一个图片URL,要提取所有的话,更推荐用下面的PHP脚本方法。
方法二:PHP脚本批量提取
在WordPress根目录新建extract-images.php文件,写入以下代码:
<?php require_once('wp-load.php'); // 查询所有已发布的文章和页面 $query = new WP_Query(array( 'post_type' => array('post', 'page'), 'post_status' => 'publish', 'posts_per_page' => -1, 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, )); $used_images = array(); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); $content = get_the_content(); // 匹配所有符合格式的图片URL preg_match_all('/https?:\/\/example\.com\/wp-content\/uploads\/[^"\'<>]+/i', $content, $matches); if (!empty($matches[0])) { $used_images = array_merge($used_images, $matches[0]); } } wp_reset_postdata(); } // 去重后输出 $used_images = array_unique($used_images); foreach ($used_images as $url) { echo $url . "\n"; } ?>
- 替换
example\.com为你的站点域名 - 访问这个脚本的URL(比如
https://你的域名.com/extract-images.php),页面会直接列出所有被使用的图片URL,复制保存即可 - 用完记得删掉这个脚本,防止安全隐患
注意点
- 以上方法只提取文章/页面内容里直接写的图片URL,短代码、自定义字段或者主题模板调用的图片不会被提取到,如果有这类场景,需要额外处理。
- 拿到URL列表后,把对应文件备份,就可以清理媒体库中不在列表里的冗余图片了。
内容的提问来源于stack exchange,提问作者Faizan Ahmed
相关产品推荐
相关产品推荐

