腾讯云服务器优惠活动华纳云香港服务器

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

WordPress主题推荐

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

第一步:在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="'. get_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文章列表自动调用文章缩略图-第1张-boke112百科(boke112.com)

本文地址:https://boke112.com/post/146.html

赞 (0) 打赏
版权声明:本文为原创文章,版权归 boke112百科 所有,欢迎分享本文,转载请保留出处!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu