WordPress封面图方案
我有个坏习惯,不太喜欢在发布文章的时候手动设置特色图片,为了把这个坏习惯贯彻到底,我使用的封面图方案是:若文章中有图片,便自动使用文章中第一张图片作为封面图,若文章中无图,便给文章自动来一张默认封面图,若手动设置了文章特色图便使用后台设置的特色图片作为封面图。
下面是我编写的代码,你只需要把下面代码粘贴在你主题function.php文件中也可以实现和我一样的封面图方案。
//获取文章封面
function yumu_the_post_thumbnail($postID) {
$already_has_thumb = has_post_thumbnail($postID);
if($already_has_thumb){
$thumb_id = get_post_thumbnail_id($postID);
$thumb = wp_get_attachment_image_src($thumb_id, 'full');
$thumb = $thumb[0];
}else{
$attached_image = get_children( "post_parent=$postID&post_type=attachment&post_mime_type=image&numberposts=3" );
if ($attached_image){
foreach ($attached_image as $attachment) {
$thumb = $attachment->guid;
}
}else{
$thumbarr=Array(
'默认图片链接1',
'默认图片链接2',
);
$rndthumb = array_rand($thumbarr);
$thumb = $thumbarr[$rndthumb];
}
}
return $thumb;
}
最后在主题中调用文章封面图的地方调用yumu_the_post_thumbnail()函数。
如下方式调用
<?php echo yumu_the_post_thumbnail($post->ID,1);?>