WordPress自动设置文章第一个图片为特色图像

大家在写文章的时候可能会忘记设定特色图像,而有的主题必须设置特色图像在会在相应的位置显示,所以这里有一个办法,自动调用文章中第一个图片来作为wordpress的特色图像。
将下面的代码放到你主题的functions.php文件 ?> 之前:

/* 設定所有文章第一個為特色圖片開始*/
function autoset_featured_image(){
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);
}
}
}
}
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');
/* 設定所有文章第一個為特色圖片結束*/

此处评论已关闭