最近在折腾主题的时候,我想让图片显示得更加规范一点,比如显示多张,总不能总是获取第一张图片做缩略图,DIY自定义一下。
在百毒搜索一番没有找到确实答案,于是一番折腾在Joe主题找到大部分答案,我把代码记录下,一通Ctrl+C+V。
/ 自定义图片缩略图 / $thumb = new Typecho_Widget_Helper_Form_Element_Textarea( 'thumb', NULL, NULL, '自定义缩略图(非必填)', '填写时:将会显示填写的文章缩略图 <br> 不填写时:<br> 1、若文章有图片则取文章内图片 <br> 2、若文章无图片,并且外不雅观设置里未填写·自定义缩略图·选项,则取模板自带图片 <br> 3、若文章无图片,并且外不雅观设置里填写了·自定义缩略图·选项,则取自定义缩略图图片 <br> 把稳:多个缩略图时换行填写,一行一个(仅在三图模式下生效)' ); $layout->addItem($thumb);/ 多张缩略图 / $JThumbnail = new Typecho_Widget_Helper_Form_Element_Textarea( 'JThumbnail', NULL, NULL, '自定义缩略图', '先容:用于修正主题默认缩略图 <br/> 格式:图片地址,一行一个 <br /> 把稳:不填写时,则利用主题内置的默认缩略图 ' ); $JThumbnail->setAttribute('class', 'joe_content joe_image'); $form->addInput($JThumbnail);/ 获取列表缩略图 /function _getThumbnails($item){ $result = []; $pattern = '/\<img.?src\=\"(.?)\"[^>]>/i'; $patternMD = '/\!\[.?\]\((http(s)?:\/\/.?(jpg|jpeg|gif|png|webp))/i'; $patternMDfoot = '/\[.?\]:\s(http(s)?:\/\/.?(jpg|jpeg|gif|png|webp))/i'; / 如果填写了自定义缩略图,则优先显示填写的缩略图 / if ($item->fields->thumb) { $fields_thumb_arr = explode("\r\n", $item->fields->thumb); foreach ($fields_thumb_arr as $list) $result[] = $list; } / 如果匹配到正则,则连续补充匹配到的图片 / if (preg_match_all($pattern, $item->content, $thumbUrl)) { foreach ($thumbUrl[1] as $list) $result[] = $list; } if (preg_match_all($patternMD, $item->content, $thumbUrl)) { foreach ($thumbUrl[1] as $list) $result[] = $list; } if (preg_match_all($patternMDfoot, $item->content, $thumbUrl)) { foreach ($thumbUrl[1] as $list) $result[] = $list; } / 如果上面的数量不敷3个,则直接补充3个随即图进去 / if (sizeof($result) < 3) { $custom_thumbnail = Helper::options()->JThumbnail; / 将for循环放里面,减少一次if判断 / if ($custom_thumbnail) { $custom_thumbnail_arr = explode("\r\n", $custom_thumbnail); for ($i = 0; $i < 3; $i++) { $result[] = $custom_thumbnail_arr[array_rand($custom_thumbnail_arr, 1)] . "?key=" . mt_rand(0, 1000000); } } else { / 自定义随机图片 / for ($i = 0; $i < 3; $i++) { $result[] = 'https://cdn.jsdelivr.net/npm/typecho-joe-next@6.0.0/assets/thumb/' . rand(1, 42) . '.jpg'; } } } return $result;}
还可以根据自己需求进行修正代码,来实现相应的效果。

在首页或者文章页调用
<?php echo _getThumbnails($item)[0]; ?>
调用多张图片
<?php $image = _getThumbnails($this) ?><?php for ($x = 0; $x < 3; $x++) : ?>/ 调用 /<?php echo $image[$x]; ?>