圖片可以為網(wǎng)站增加很多可讀性,WordPress 內(nèi)置了強(qiáng)大的縮略圖系統(tǒng),可以根據(jù)設(shè)置的尺寸自動輸出壓縮后的圖片,這樣就不會因?yàn)椴恍⌒纳蟼髁吮容^大的圖片而導(dǎo)致網(wǎng)站打開速度慢了。
然而有時候,我們在文章上上傳了圖片,卻忘記了上傳縮略圖,這時候有些需要顯示縮略圖的主題顯示可能就不正常了,這當(dāng)然是我們不希望看到的。下面的一段代碼可以自動提取文章里面的第一張圖片作為文章的縮略圖。
具體實(shí)現(xiàn)思路是,首先判斷是不是自動保存的修訂版本,然后判斷當(dāng)前編輯的是否為文章,最后判斷是否手動設(shè)置了縮略圖,如果都不是,調(diào)取文章附件中的第一張圖片,設(shè)置為文章的縮略圖。
add_action( 'save_post', function( $post_id ) {
if ( wp_is_post_revision( $post_id ) )
return NULL;
if ( ! isset( $post_id ) )
return NULL;
if ( has_post_thumbnail( $post_id ) )
return NULL;
$args = array(
'numberposts' => 1,
'order' => 'DESC', // DESC for the last image
'post_mime_type' => 'image',
'post_parent' => $post_id,
'post_status' => NULL,
'post_type' => 'attachment'
);
$attached_image = get_children( $args );
if ( $attached_image ) {
foreach ( $attached_image as $attachment_id => $attachment )
set_post_thumbnail( $post_id, $attachment_id );
}
}
有了這段代碼,不但不會因?yàn)橥浬蟼骺s略圖而導(dǎo)致主題顯示錯誤,在縮略圖和文章的第一篇圖片是一張圖片的時候,還可以省掉一個手動上傳縮略圖的步驟,一舉兩得!



你好!
我在 functions.php里面<?php 后面插入以上代碼,但是依然未能實(shí)現(xiàn)文章列表中顯示第一張圖片,請問可否具體告知下怎么做?