在博客首页显示缩略图的方法(非插件)
在主题的functions.php中插入如下方法并保存:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /** 输出文章缩略图 */ function showThumbnail($widget) { // 当文章无图片时的默认缩略图 $rand = rand(1,5); // 随机 1-5 张缩略图 $random = $widget->widget('Widget_Options')->themeUrl . '/img/sj/' . $rand . '.jpg'; // 随机缩略图路径 // $random = $widget->widget('Widget_Options')->themeUrl . '/img/mr.jpg'; // 若只想要一张默认缩略图请删除本行开头的"//" $attach = $widget->attachments(1)->attachment; $pattern = '/\<img.*?src\=\"(.*?)\"[^>]*>/i'; if (preg_match_all($pattern, $widget->content, $thumbUrl)) { echo $thumbUrl[1][0]; } else if ($attach->isImage) { echo $attach->url; } else { echo $random; } } |
然后在要显示缩略图的地方插入如下代码启用:
1 | <img style="float:left;margin:5px;word-break: break-all;" src="<?php showThumbnail($this); ?>" width=120 height=100 /> |
宽度和高度请自行调整,width是宽,height是高度
添加随机图片作为缩略图的方法:
在主题img文件夹下新建sj文件夹,依次放入1.jpg,2.jpg...~5.jpg,如果要更改随机图片的数量,或只想要一张默认的缩略图,请先按照注释修改好代码,然后在主题img文件夹放入mr.jpg文件。