首先需要说明的是只能获取本地图片,远程图片无法获取。然后获取的是上传到附件库的最前面的一张图片、可能并不是文章的第一张图。
一段代码搞定,方法如下:复制下面的代码放置到主题文件 functions.php 的结束标签前即可。
function autoset_featured() {
global $post;
$already_has_thumb = has_post_thumbnail($post->ID);
if (!$already_has_thumb) {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment_id);
}
}
}
} //end function
add_action(’the_post’, ’autoset_featured’);
add_action(’save_post’, ’autoset_featured’);
add_action(’draft_to_publish’, ’autoset_featured’);
add_action(’new_to_publish’, ’autoset_featured’);
add_action(’pending_to_publish’, ’autoset_featured’);
add_action(’future_to_publish’, ’autoset_featured’);
分享喵