将文章首张图作为缩略图,除了插件外,也大都是通过在主题functions.php添加函数代码的方法来实现的。
第一步:在主题functions.php文件中添加以下代码:
function get_postthumb($this) { preg_match_all( "/<[img|IMG].*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/", $this->content, $matches ); //通过正则式获取图片地址 if(isset($matches[1][0])){ $thumb = $matches[1][0]; } return $thumb; }
其主要实现原理是:通过正则表达式匹配文章内容的img标签获取src的图片地址。
第二步:调用代码
<img src="<?php echo get_postthumb($this); ?>">