Hi!请登陆

WordPress文章列表自动调用文章缩略图

2021-1-5 46 1/5

前几天我的那个懿古今博客改变定位后,主要分享科技资讯、人在职场和健康生活方面的文章,而现使用主题的文章列表是纯文字,感觉没有那么赏心悦目,所以决定增加自动调用文章缩略图功能。经过在网上搜索相关知识发现,其实还是挺简单的,只需要三步即可实现。

第一步:在functions.php文件里添加以下函数

//文章列表缩略图
function emtx_auto_thumbnail($pID,$thumb='thumbnail') {
$blogimg = FALSE;
if (has_post_thumbnail()) {
$blogimg = wp_get_attachment_image_src(get_post_thumbnail_id($pID),$thumb);
$blogimg = $blogimg[0];
} elseif ($postimages = get_children("post_parent=$pID&post_type=attachment&post_mime_type=image&numberposts=0")) {
foreach($postimages as $postimage) {
$blogimg = wp_get_attachment_image_src($postimage->ID, $thumb);
$blogimg = $blogimg[0];
}
} elseif (preg_match('/<img [^>]*src=["|\']([^"|\']+)/i', get_the_content(), $match) != FALSE) {
$blogimg = $match[1];
}
if($blogimg) {
$blogimg = '<a href="'.%20get_permalink().'"><img src="'.$blogimg.'" alt="'.get_the_title().'" class="alignleft wp-post-image" /></a>';
}
return $blogimg;
}

第二步:在首页和文章列表页文件中添加以下代码

<div class="thumbnail">
<?php if(emtx_auto_thumbnail($post->ID) ) {
echo emtx_auto_thumbnail($post->ID);
} ?>
</div>

第三步:在style.css文件中添加如下代码

/* 缩略图*/
.thumbnail {
position: relative;
float: left;
margin: 6px 10px 0 0;
}
.thumbnail a img {
width: 200px;
height: 130px;
}

完成这三步后,就可以实现文章列表自动调用文章中的缩略图了,具体效果如下图所示:

WordPress文章列表自动调用文章缩略图

相关推荐