Typecho纯代码输出文章缩略图

Typecho是一个很好的博客程序,很多东西可以DIY,比如可以纯代码输出文章缩略图。采用文章第一张图片作为缩略图,无论是文章附件图片或者网络图片均可,当文章无图片时的可设置为默认缩略图或者随机图片或者分类图片。到主题functions.php文件插入以下代码:

代码1:无图时默认图片

function showThumbnail($widget)
{
// 当文章无图片时的默认缩略图
$random = $widget->widget('Widget_Options')->themeUrl . '/wp-content/files/0.jpg'; // 默认缩略图路径
$attach = $widget->attachments(1)->attachment;
$pattern = '/\]*>/i';
if (preg_match_all($pattern, $widget->content, $thumbUrl)) {
echo $thumbUrl[1][0];
} else if ($attach->isImage) {
echo $attach->url;
} else {
echo $random;
}
}
代码2:无图时随机图片

function showThumbnail($widget)
{
// 当文章无图片时的随机缩略图
$rand = rand(1,9); // 随机 1-9 张缩略图
$random = $widget->widget('Widget_Options')->themeUrl . '/rand/' . $rand . '.jpg'; // 随机缩略图路径
$attach = $widget->attachments(1)->attachment;
$pattern = '/\]*>/i';
if (preg_match_all($pattern, $widget->content, $thumbUrl)) {
echo $thumbUrl[1][0];
} else if ($attach->isImage) {
echo $attach->url;
} else {
echo $random;
}
}
代码3:无图时分类图片

function showThumbnail($widget)
{
// 当文章无图片时的分类缩略图
$cate = $widget->categories[0]['mid']; // 分类的id缩略图
$random = $widget->widget('Widget_Options')->themeUrl . '/cate/' . $cate . '.jpg'; // 分类缩略图路径
$attach = $widget->attachments(1)->attachment;
$pattern = '/\]*>/i';
if (preg_match_all($pattern, $widget->content, $thumbUrl)) {
echo $thumbUrl[1][0];
} else if ($attach->isImage) {
echo $attach->url;
} else {
echo $random;
}
}
使用方法:
在主题中对应位置加入:

注意事项:
1、代码1需要在主题文件夹下建立img文件夹,放入默认图片0.jpg;

2、代码2需要在主题文件夹下建立rand文件夹,放入随机9张图片,并依次重命名为1.jpg、2.jpg直到9.jpg;

3、代码3需要在主题文件夹下建立cate文件夹,并根据分类的cid放入图片,并将cid命名为图片名,图片后缀为.jpg;

4、图片文件夹和后缀都可以修改,请自行修改。

发表新评论