wordpress自動設置第一張圖為特色圖片代碼
將下方代碼添加到當前主題的functions.php中
function wpforce_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' , 'wpforce_featured' ) ;
add_action ( 'save_post' , 'wpforce_featured' ) ;
add_action ( 'draft_to_publish' , 'wpforce_featured' ) ;
add_action ( 'new_to_publish' , 'wpforce_featured' ) ;
add_action ( 'pending_to_publish' , 'wpforce_featured' ) ;
add_action ( 'future_to_publish' , 'wpforce_featured' ) ;
上面的代碼就會設置文章內的第一張圖為特色圖片。但是有時候我們文章裡沒有圖片怎麼辦?
可以用下面的代碼,設置某一個ID的圖片為默認圖片。
function wpforce_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 ) ;
}
} else {
set_post_thumbnail ( $post - > ID , '8888' ) ;
}
}
} //end function
add_action ( 'the_post' , 'wpforce_featured' ) ;
add_action ( 'save_post' , 'wpforce_featured' ) ;
add_action ( 'draft_to_publish' , 'wpforce_featured' ) ;
add_action ( 'new_to_publish' , 'wpforce_featured' ) ;
add_action ( 'pending_to_publish' , 'wpforce_featured' ) ;
add_action ( 'future_to_publish' , 'wpforce_featured' ) ;
上面代碼裡的$post->ID, ‘8888’這個8888就是圖片ID,自己在網站媒體庫找一張圖改一下ID吧。