
很多 WordPress 博客的主题都设计了显示文章缩略图,但其中大部分都要手动添加“特色图像”,显然很麻烦。所以最好的方法便是自动获取,自动显示文章第一张图片。
1、在当前使用的主题模板的 functions.php 文件之前添加以下代码,
function catch_that_image() { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $first_img = $matches [1] [0]; if(empty($first_img)){ //Defines a default image $first_img = "/images/default.jpg"; } return $first_img; }

2、在分类页 (Twenty Fifteen: content-search.php) 加入代码
<div style="text-align:center; padding-bottom:10px;"> <a href="<?php the_permalink(); ?>"> <img src="<?php echo catch_first_image() ?>" alt="<?php the_title(); ?>"/> </a> </div>

效果如下:
