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

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

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

  1. //文章列表缩略图
  2. function emtx_auto_thumbnail($pID,$thumb='thumbnail') {
  3. $blogimg = FALSE;
  4. if (has_post_thumbnail()) {
  5. $blogimg = wp_get_attachment_image_src(get_post_thumbnail_id($pID),$thumb);
  6. $blogimg = $blogimg[0];
  7. } elseif ($postimages = get_children("post_parent=$pID&post_type=attachment&post_mime_type=image&numberposts=0")) {
  8. foreach($postimages as $postimage) {
  9. $blogimg = wp_get_attachment_image_src($postimage->ID, $thumb);
  10. $blogimg = $blogimg[0];
  11. }
  12. } elseif (preg_match('/<img [^>]*src=["|\']([^"|\']+)/i', get_the_content(), $match) != FALSE) {
  13. $blogimg = $match[1];
  14. }
  15. if($blogimg) {
  16. $blogimg = '<a href="'. get_permalink().'"><img src="'.$blogimg.'" alt="'.get_the_title().'" class="alignleft wp-post-image" /></a>';
  17. }
  18. return $blogimg;
  19. }

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

  1. <div class="thumbnail">
  2. <?php if(emtx_auto_thumbnail($post->ID) ) {
  3. echo emtx_auto_thumbnail($post->ID);
  4. } ?>
  5. </div>

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

  1. /* 缩略图*/
  2. .thumbnail {
  3. position: relative;
  4. float: left;
  5. margin: 6px 10px 0 0;
  6. }
  7. .thumbnail a img {
  8. width: 200px;
  9. height: 130px;
  10. }

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

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

© 版权声明
THE END
喜欢就支持一下吧