如何让WordPress自动将文章首图设为Featured Image?
解决方案:自动将文章首图设为WordPress特色图片
一、批量处理已有旧文章
可以通过PHP代码一次性处理所有未设置特色图片的文章,操作步骤如下:
- 将以下代码添加到主题的
functions.php文件末尾(操作前请务必备份网站数据):
function auto_set_featured_image_from_first_external_img() { // 查询所有未设置特色图片的已发布文章 $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => '_thumbnail_id', 'compare' => 'NOT EXISTS' ) ) ); $posts = get_posts($args); foreach ($posts as $post) { // 提取文章内容中的第一张图片URL preg_match('/<img[^>]+src="([^">]+)"/i', $post->post_content, $matches); if (!empty($matches[1])) { $image_url = $matches[1]; // 判定为外链图片(非本站域名) if (strpos($image_url, home_url()) === false) { // 下载图片到WordPress媒体库 $attachment_id = media_sideload_image($image_url, $post->ID, '', 'id'); if (!is_wp_error($attachment_id)) { // 将下载后的图片设置为文章特色图片 set_post_thumbnail($post->ID, $attachment_id); echo '已为文章ID ' . $post->ID . ' 设置特色图片<br>'; } } } } } // 调用函数执行批量处理(执行完成后请注释掉这一行,避免重复执行) // auto_set_featured_image_from_first_external_img();
- 保存文件后,访问网站任意页面触发代码执行。处理完成后,必须注释掉最后一行的函数调用代码,防止每次加载页面都重复运行批量处理逻辑。
提示:如果文章数量超过1万篇,建议分批次处理——将
posts_per_page的值改为500,多次执行直到所有文章处理完毕,避免服务器超时。
二、自动处理新文章/未处理的旧文章
如果不想一次性批量处理,可以添加实时检测代码,每次访问文章时自动检查并设置特色图片:
function auto_set_featured_image_on_load($post_id) { // 仅处理已发布且未设置特色图片的文章 if (get_post_status($post_id) !== 'publish' || has_post_thumbnail($post_id)) { return; } $post = get_post($post_id); preg_match('/<img[^>]+src="([^">]+)"/i', $post->post_content, $matches); if (!empty($matches[1])) { $image_url = $matches[1]; if (strpos($image_url, home_url()) === false) { $attachment_id = media_sideload_image($image_url, $post_id, '', 'id'); if (!is_wp_error($attachment_id)) { set_post_thumbnail($post_id, $attachment_id); } } } } add_action('template_redirect', 'auto_set_featured_image_on_load');
将上述代码添加到functions.php中即可,每次访问未设置特色图片的文章时,会自动提取首图并设置为特色图片。
注意事项
- 操作前务必备份网站数据库和文件,避免数据丢失。
- 批量处理大量文章会占用服务器资源,建议在网站访问低峰时段执行。
- 确保外链图片的使用符合版权要求,避免侵权风险。
内容的提问来源于stack exchange,提问作者DannyM
相关产品推荐
相关产品推荐

