介绍

顺序是:thumb(自定义字段)--> 第一个图片附件--> 文章第一张图片 --> 随机图片输出

代码扒了Themia的主题

在function.php 加上这段代码

function showThumbnail($widget) { // 当文章无图片时的默认缩略图 $rand = rand(1,7); // 随机 1-7 张缩略图 $random = $widget->widget('Widget_Options')->themeUrl . '/images/sj/' . $rand . '.jpg'; // 随机缩略图路径 //正则匹配 主题目录下的/images/sj/的图片(以数字按顺序命名) $cai = ''; $attach = $widget->attachments(1)->attachment; $pattern = '/\<img.*?src\=\"(.*?)\"[^>]*>/i'; $patternMD = '/\!\[.*?\]\((http(s)?:\/\/.*?(jpg|png))/i'; $patternMDfoot = '/\[.*?\]:\s*(http(s)?:\/\/.*?(jpg|png))/i'; if ($attach && $attach->isImage) { $ctu = $attach->url.$cai; } //调用第一个图片附件 else //下面是调用文章第一个图片 if (preg_match_all($pattern, $widget->content, $thumbUrl)) { $ctu = $thumbUrl[1][0].$cai; } //如果是内联式markdown格式的图片 else if (preg_match_all($patternMD, $widget->content, $thumbUrl)) { $ctu = $thumbUrl[1][0].$cai; } //如果是脚注式markdown格式的图片 else if (preg_match_all($patternMDfoot, $widget->content, $thumbUrl)) { $ctu = $thumbUrl[1][0].$cai; } //以上都不符合,即随机输出图片 else { $ctu = $random; } return $ctu; }

修改index.php 里面的代码

<?php if (array_key_exists('thumb',unserialize($this->___fields()))): ?> <div class="index-post-thumb"> <a class="index-post-cover" href="<?php $this->permalink() ?>"> <img class="thumb" src="<?php echo $this->fields->thumb;?>"> </a> </div> <?php else : ?> <?php $thumb = showThumbnail($this); if(!empty($thumb)):?> <div class="index-post-thumb"> <a class="index-post-cover" href="<?php $this->permalink() ?>"> <img class="thumb" src="<?php echo $thumb;?>"> </a> </div> <?php endif; ?> <?php endif; ?>

其中的第一段

if (array_key_exists('thumb',unserialize($this->___fields())))

用来判断是否有thumb 自定义字段。如果有,则输出自定义字段的图片地址。


最后修改:2019 年 02 月 24 日
喜欢我的文章吗?
别忘了点赞或赞赏,让我知道创作的路上有你陪伴。