主题实际已经设置自动搜索文章第一张图片作为缩略图了,但是有时候图片太大就导致了缩略图也很大,加载反而变慢,又懒得每次手动设置特色图像,所以这段代码可以自动把文章中上传的第一张图片设置为特色图像,缺点就是不支持外链图片!
//从文章中获取第一张图片作为缩略图
function autoset_featured_image() {
global $post;
if (!is_object($post)) return;
$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);
}
}
}
}
add_action( 'the_post', 'autoset_featured_image' );
add_action( 'save_post', 'autoset_featured_image' );
add_action( 'draft_to_publish', 'autoset_featured_image' );
add_action( 'new_to_publish', 'autoset_featured_image' );
add_action( 'pending_to_publish', 'autoset_featured_image' );
add_action( 'future_to_publish', 'autoset_featured_image' );
© 版权声明
THE END
暂无评论内容