打开一篇文章,看到底下的“猜你喜欢”推荐了一篇旧日志,中间一篇没有特色图片,真的很难看,而我又懒,不想一篇篇的去添加,所以找了段代码,加上去了,哦豁,完美就是这般呈现的。
这个东西,就是没有自主设定特色图片的文章,会给你自动加上一幅特色图片,有两种呈现方式,都是将代码加入到主题的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');
但是有的文章本身就没有配图,所以上面的那款并不适合我这边,那就是有下面的一种,可以指定一张图作为特色图片,就是你文章纵使没有图,也会给你配上特色图,就不会有空啦。下面的那个“999999999”就是指定的特色图片的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, '999999999');
}
}
} //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');
然后发现一个问题,这是文章页和页面页都添加了特色图片,但是我的页面并不想加,所以,我又给这个代码删了,但是添加的特色图片就再上面了,还是很不错的,手动把页面的特色图片给删了,真实完美。