教程:从文章内容中自动设置特色图像

如果您是 WordPress 的重度编辑,您可能会发现大多数时候,您只是将文章的第一张图片设置为特色图像。这是一种快速方便的方法,可以帮助您跳过繁琐的工作并节省一些劳动力。下面是可用的代码。


/**
 * Automatically set featured image for posts without one.
 */function set_featured_image_on_save($post_id) {
    // Check if post type supports featured image
    $post_type = get_post_type($post_id);
    
   if (!post_type_supports($post_type, 'thumbnail')) { // the 'thumbnail' feature, which is used for featured image
        return;
    }
    
    // Check if post has a featured image
    if (has_post_thumbnail($post_id)) {
        return;
    }
    
    // Get the post content
    $post = get_post($post_id);
    $post_content = $post->post_content;
    
    // Search content for images
    $pattern = '/]+src=[\'"]([^\'"]+)[\'"][^>]*>/i';
    preg_match($pattern, $post_content, $matches);
    
    if (isset($matches[1])) {
        $image_url = $matches[1];
        
        // Check if the image is already in the media library
        $attach_id = attachment_url_to_postid($image_url);
        
        // If the image doesn't exist in the media library, add it
        if (empty($attach_id)) {
            $upload_dir = wp_upload_dir();
            $image_data = file_get_contents($image_url);
            $filename = basename($image_url);
            
            if (wp_mkdir_p($upload_dir['path'])) {
                $file = $upload_dir['path'] . '/' . $filename;
            } else {
                $file = $upload_dir['basedir'] . '/' . $filename;
            }
            
            file_put_contents($file, $image_data);
            
            $wp_filetype = wp_check_filetype($filename, null);
            $attachment = array(
                'post_mime_type' => $wp_filetype['type'],
                'post_title' => sanitize_file_name($filename),
                'post_content' => '',
                'post_status' => 'inherit'
            );
            
            $attach_id = wp_insert_attachment($attachment, $file, $post_id);
            $attach_data = wp_generate_attachment_metadata($attach_id, $file);
            wp_update_attachment_metadata($attach_id, $attach_data);
        }
        
        // Add the image as the featured image for the post
        set_post_thumbnail($post_id, $attach_id);
    }
}

add_action('save_post', 'set_featured_image_on_save');

本代码只适用自己写文章的情况下设置第一张图为特色图像。如果是采集的。请绕道,本人鄙视任何采集。

使用时请获知以下情况:

  • 如不生效:确保您的 WordPress 具有读取和写入文件到上传目录的必要权限。
  • 性能问题:如果您的文章包含大量图像,则此代码可能会减慢保存过程,因为它必须下载和处理图像。
  • 图像选择:代码使用在文章中找到的第一张图片。如果您希望使用其他图片作为特色图片,则需要手动设置。
  • 文章类型:默认情况下,此功能适用于所有支持“缩略图”功能的文章类型。如果要将其限制为特定的文章类型,则需要修改代码。

本文已在Ie主题99839发布

文章来源:https://ietheme.com/automatically-set-featured-image-from-post-content.html


撰写评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

加入我们

注册完成!

密码重置

请输入您的邮箱地址。 您将收到一个链接来创建新密码。

检查你的邮件中的确认链接。