教程介绍
这是一篇为WordPress自动调用特色图像的代码,现在很的主题都自带了这功能,但是也有部分主题没有,比如DUX主题,那么就造成了一个问题之前网站的缩略图可以显示换了某个主题后就不显示了,需要设置特色图像,但是我文章很多一篇一篇的设置太麻烦了,所以就有了这篇教程。
将以下代码添加到当前使用主题的functions.php文件中即可。
代码预览
function autoset_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', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');
评论2