最近在折腾主题的时候,我想让图片显示得更加规范一点,比如显示多张,总不能老是获取第一张图片做缩略图,DIY自定义一下。

百毒搜索一番没有找到确实答案,于是一番折腾在Joe主题找到大部分答案,我把代码记录下,一通Ctrl+C+V。

在主题的functions.php添加以下代码

PLAINTEXT
/* 自定义图片缩略图 */
    $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;
}
点击展开查看更多

还可以根据自己需求进行修改代码,来实现相应的效果。

模板调用函数

在首页或者文章页调用

PLAINTEXT
<?php echo _getThumbnails($item)[0]; ?>
点击展开查看更多

调用多张图片

PLAINTEXT
<?php $image = _getThumbnails($this) ?>
<?php for ($x = 0; $x < 3; $x++) : ?>
/* 调用 */
<?php echo $image[$x]; ?>
点击展开查看更多

版权声明

作者: JunYan`Blog

链接: https://www.jinjun.top/posts/tyimg/

许可证: CC BY-NC-SA 4.0

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Please attribute the source, use non-commercially, and maintain the same license.

评论

开始搜索

输入关键词搜索文章内容

↑↓
ESC
⌘K 快捷键