WordPress在发布或更新文章设置内容中的第一张图片为缩略图

要实现在发布或更新文章时自动将内容中的第一张图片设置为缩略图,可以通过添加以下代码到主题的functions.php文件或自定义插件中。这段代码会在文章保存时自动检测并设置缩略图。

WordPress在发布或更新文章设置内容中的第一张图片为缩略图的配图 - Haida(嗨达)主题演示
// 自动将文章内容中的第一张图片设置为缩略图
function auto_set_featured_image($post_id) {
    // 检查是否为自动保存
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    // 检查用户权限
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    // 如果已经设置了缩略图,则不执行
    if (has_post_thumbnail($post_id)) {
        return;
    }
    
    // 获取文章内容
    $post_content = get_post_field('post_content', $post_id);
    
    // 从内容中提取第一张图片
    preg_match('/<img[^>]+src=[\'"]([^\'"]+)[\'"]/i', $post_content, $matches);
    
    if (!empty($matches[1])) {
        $image_url = $matches[1];
        
        // 处理相对路径
        if (strpos($image_url, site_url()) === false) {
            $image_url = site_url() . $image_url;
        }
        
        // 尝试获取图片附件ID
        $attachment_id = attachment_url_to_postid($image_url);
        
        // 如果图片已存在于媒体库中
        if ($attachment_id) {
            set_post_thumbnail($post_id, $attachment_id);
        } else {
            // 如果图片不在媒体库中,尝试下载并添加
            require_once(ABSPATH . 'wp-admin/includes/media.php');
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            
            // 下载图片并添加到媒体库
            $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('save_post', 'auto_set_featured_image');

代码功能说明:

这段代码的工作原理如下:

  1. 钩子到save_post动作,在文章发布或更新时触发
  2. 首先检查是否为自动保存或用户是否有编辑权限
  3. 如果已经设置了缩略图,则不执行任何操作
  4. 从文章内容中提取第一张图片的 URL
  5. 检查该图片是否已存在于媒体库中:
    • 如果存在,直接将其设置为缩略图
    • 如果不存在,尝试下载图片并添加到媒体库,然后设置为缩略图

使用注意事项:

  • 代码会处理站内图片和外链图片
  • 只有在文章没有设置缩略图的情况下才会执行
  • 对于已发布的文章,更新时也会触发此功能
  • 图片下载功能可能会受到服务器安全设置或外部网站防盗链的限制

如果需要限制此功能只对特定文章类型生效,可以在函数开头添加文章类型检查,例如:

// 只对post类型生效
if (get_post_type($post_id) !== 'post') {
    return;
}

标签
THE END
喜欢就支持一下吧

相关推荐

评论

抢沙发
G
Guest
No Comment
There's nothing here!