Typecho用functions.php实现文章缩略图的方法

Typecho是一款基于PHP5开发的轻量级开源博客程序,名称由“type”与“echo”组合而成,支持MySQL、PostgreSQL、SQLite等多种数据库,代码量不足400KB且仅需7张数据表实现功能,采用MVC架构与模块化设计。遵循GPLv2协议发行,提供插件机制、主题模板引擎及原生Markdown支持,具有内核强健、扩展方便、体验友好、运行流畅等特性。

1.编辑 functions.php 文件

在其中加入以下代码:

/**
* 输出文章缩略图
*
* @author ShingChi
* @access public
* @param int $width 缩略图宽度 
* @param int $height 缩略图高度
* @return viod
* @version Release 1.0.4
*/
function getThumbnAIl($widget, $width, $height)
{
$options = $widget->widget('Widget_Options');

/** 默认图片目录、后缀 */
$path = $options->themeUrl . '/images/category/'; // 路径:模板文件夹/images/category/图片为分类缩略名
$suffix = '.jpg';

/** 文章相关 */
$cid = $widget->cid;
$title = $widget->title;
$content = $widget->text;
$category = $widget->category;
$link = $widget->permalink;

$db = Typecho_Db::get();
$sql = $db->select('text')
->from('table.contents')
->where('type = ? AND parent = ?', 'attachment', $cid)
->limit(1);
$attach = $db->fetchRow($sql);

if (empty($attach)) { // 没有附件时从文章内容读取
$pattern = '/<img.*?src="(.*?)"[^>]*>/i'; // 匹配文章内容中的图片

if (preg_match_all($pattern, $content, $thumbUrl)) {
echo '<a href="' . $link . '"><img src="' . $thumbUrl[1][0] . '" width="' . $width . '" height="' . $height . '" alt="' . $title . '" /></a>';
} else {
echo '<a href="' . $link . '"><img src="' . $path . $category . $suffix . '" width="' . $width . '" height="' . $height . '" alt="' . $title . '" ></a>';
}
} else { // 从附件中读取
$attachText = unserialize($attach['text']);
$isImage = '/gif|jpg|jpeg|bmp|png/i'; // 匹配图片附件类型

if (preg_match($isImage, $attachText['type'])) {
echo '<a href="' . $link . '"><img src="' . $options->themeUrl . '/timthumb.php?src=' . $options->siteUrl . $attachText['path'] . '&q=100&w=' . $width . '&h=' . $height . '" alt="' . $title . '" /></a>';
} else {
echo '<a href="' . $link . '"><img src="' . $path . $category . $suffix . '" width="' . $width . '" height="' . $height . '" alt="' . $title . '" ></a>';
}
}
}

2.使用缩略图

2.1 去下载 timthumb.php 单文件,上传到当前模板目录下。

2.2 在当前模板的图片目录里新建一个 category 的文件夹,把所有分类的缩略图放在里面,图片命名为分类缩略名,后缀为 jpg,当然可以根据上面代码更改。

2.3 在需要输出缩略图的地方插入以下代码,如我要输出宽和高100px的缩略图:

<?php getThumbnail($this, 100, 100); ?>