介紹目前WordPress文章自動設置特色圖像的方法。WordPress的特色圖像是一個很實用的功能,為每篇文章增加一個特色圖像,可以使blog各個部分都更生動。比如首頁每篇文章都有自己的縮略圖,相關文章中用縮略圖告訴用戶這些文章的主題,或者在側欄加一個特色文章功能,顯示文章特色圖像。
現在的情況是,發布的文章,并插入了圖像后,不顯示縮略圖,原因是the_post_thumbnail
需要設置特色圖像,而大多情況是懶得一一設置。
那么使用下面的代碼吧,直接自動化為文章內的圖像自動設置為特色圖像
function sola_auto_featured_image() {
global $post;
if( has_post_thumbnail() ){
return;
}
preg_match('/<img\s[^>]*?class\s*=\s*[\'\"]([^\'\"]*?)[\'\"][^>]*?>/', $post->post_content, $matches);
$img_class = $matches[1] ?? false;
if( $img_class ){
preg_match('/wp-image-([\d]+)/', $img_class, $matchId);
$attachment_id = $matchId[1] ?? false;
if( $attachment_id ){
set_post_thumbnail($post->ID, absint($attachment_id) );
}
}
}
add_action('the_post', 'sola_auto_featured_image');
add_action('save_post_post', 'sola_auto_featured_image');
注意:add_action('the_post', 'sola_auto_featured_image')
會使這段代碼在任何文章被加載時運行,比如archive頁面,single post頁面等等。好處是被人訪問一段時間,你的所有文章就自動獲得了特色圖像,壞處就是對性能有影響。當你的特色圖像設置的差不多時,應該將這一句注釋掉。