最近在折腾主题的时候,我想让图片显示得更加规范一点,比如显示多张,总不能老是获取第一张图片做缩略图,DIY自定义一下。
在百毒搜索一番没有找到确实答案,于是一番折腾在Joe主题找到大部分答案,我把代码记录下,一通Ctrl+C+V。
在主题的functions.php添加以下代码
1/* 自定义图片缩略图 */
2 $thumb = new Typecho_Widget_Helper_Form_Element_Textarea(
3 'thumb',
4 NULL,
5 NULL,
6 '自定义缩略图(非必填)',
7 '填写时:将会显示填写的文章缩略图 <br>
8 不填写时:<br>
9 1、若文章有图片则取文章内图片 <br>
10 2、若文章无图片,并且外观设置里未填写·自定义缩略图·选项,则取模板自带图片 <br>
11 3、若文章无图片,并且外观设置里填写了·自定义缩略图·选项,则取自定义缩略图图片 <br>
12 注意:多个缩略图时换行填写,一行一个(仅在三图模式下生效)'
13 );
14 $layout->addItem($thumb);
15
16/* 多张缩略图 */
17 $JThumbnail = new Typecho_Widget_Helper_Form_Element_Textarea(
18 'JThumbnail',
19 NULL,
20 NULL,
21 '自定义缩略图',
22 '介绍:用于修改主题默认缩略图 <br/>
23 格式:图片地址,一行一个 <br />
24 注意:不填写时,则使用主题内置的默认缩略图
25 '
26 );
27 $JThumbnail->setAttribute('class', 'joe_content joe_image');
28 $form->addInput($JThumbnail);
29
30/* 获取列表缩略图 */
31function _getThumbnails($item)
32{
33 $result = [];
34 $pattern = '/\<img.*?src\=\"(.*?)\"[^>]*>/i';
35 $patternMD = '/\!\[.*?\]\((http(s)?:\/\/.*?(jpg|jpeg|gif|png|webp))/i';
36 $patternMDfoot = '/\[.*?\]:\s*(http(s)?:\/\/.*?(jpg|jpeg|gif|png|webp))/i';
37 /* 如果填写了自定义缩略图,则优先显示填写的缩略图 */
38 if ($item->fields->thumb) {
39 $fields_thumb_arr = explode("\r\n", $item->fields->thumb);
40 foreach ($fields_thumb_arr as $list) $result[] = $list;
41 }
42 /* 如果匹配到正则,则继续补充匹配到的图片 */
43 if (preg_match_all($pattern, $item->content, $thumbUrl)) {
44 foreach ($thumbUrl[1] as $list) $result[] = $list;
45 }
46 if (preg_match_all($patternMD, $item->content, $thumbUrl)) {
47 foreach ($thumbUrl[1] as $list) $result[] = $list;
48 }
49 if (preg_match_all($patternMDfoot, $item->content, $thumbUrl)) {
50 foreach ($thumbUrl[1] as $list) $result[] = $list;
51 }
52 /* 如果上面的数量不足3个,则直接补充3个随即图进去 */
53 if (sizeof($result) < 3) {
54 $custom_thumbnail = Helper::options()->JThumbnail;
55 /* 将for循环放里面,减少一次if判断 */
56 if ($custom_thumbnail) {
57 $custom_thumbnail_arr = explode("\r\n", $custom_thumbnail);
58 for ($i = 0; $i < 3; $i++) {
59 $result[] = $custom_thumbnail_arr[array_rand($custom_thumbnail_arr, 1)] . "?key=" . mt_rand(0, 1000000);
60 }
61 } else {
62 /* 自定义随机图片 */
63 for ($i = 0; $i < 3; $i++) {
64 $result[] = 'https://cdn.jsdelivr.net/npm/typecho-joe-next@6.0.0/assets/thumb/' . rand(1, 42) . '.jpg';
65 }
66 }
67 }
68 return $result;
69}
还可以根据自己需求进行修改代码,来实现相应的效果。
模板调用函数
在首页或者文章页调用
1<?php echo _getThumbnails($item)[0]; ?>
调用多张图片