下面由WordPress教程欄目給大家介紹自動為WordPress文章添加特色圖像的方法,希望對大家的WordPress仿站有所幫助!
WordPress的特色圖像是一個很實用的功能,可以在文章列表中為每篇文章添加一張縮略圖。但特色圖像需要在編輯文章時手動添加很不方便,下面的代碼可自動將文章中的第一張圖片設(shè)置為特色圖像。
將下面的代碼添加到當前主題的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');
如果當前文章中沒有圖片,但又想顯示一張默認的縮略圖該怎么辦,可以將上面的代碼修改一下,調(diào)用媒體庫中某個圖片作為默認的縮略圖:
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, '414'); } } } //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');
其中的數(shù)字414,是媒體庫中某個圖片附件的ID號。
提示
上面的代碼只是一篇技術(shù)文章,可能會影響到之前添加的特色圖像,所以不要輕易在自己的網(wǎng)站上做試驗。
特色圖像只適合不在乎空間流量和大小的用戶使用,因為每張圖片都會裁剪成多張大小不同的縮略圖方便在不同的位置調(diào)用,最主要的是不支持外鏈,很浪費空間….