【本文最后由 Twtte.com 更新于 2024-08-30. 如果有相关的资源失效,请留言反馈,将会及时处理。】
Featured Image 特色图像/缩略图代表帖子或页面的内容、情绪或主题,并用于整个网站。本指南将向您展示如何在网站上使用精选图片。
精选图片通常被称为“缩略图”,在各种布局中突出显示在帖子顶部或旁边,使其成为吸引读者和传达内容精髓的重要组成部分。
在 WordPress 领域,特色图像/缩略图(Featured Image)是增强帖子或页面美感和功能性的关键视觉元素。
大多数时候,如果您是 WordPress 的重度编辑,您可以通过代码实现将WordPress文章(article/post)的第一张图片设置为特色图像(Featured Image)。
这是一种快速方便的代码可实现的方法,可以帮助您跳过繁琐的工作并节省时间和体力。
下面是可用的PHP代码。(本代码不支持采集器/采集文章来源。)
/**
* 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 中设置缩略图是一个简单的过程:
常规情况下,如果我们想要替换WordPress的缩略图,需要打开文章,点击编辑文章,然后点击替换特色图像/缩略图(Featured Image)操作;
但是如果大量文章的特色图像/缩略图(Featured Image)替换,这样的逐个打开文章编辑的方法就会耗费大量的时间,很无趣。
推荐使用WordPress的特色图像/缩略图插件:Quick Featured Images
quick-featured-images.zip
从您的计算机中选择quick-featured-images.zip
quick-featured-images
到您的计算机quick-featured-images
目录上传到/wp-content/plugins/
目录