typecho按需求输出缩略图
代码来自 pinghsu 主题,有改动
在function.php 加上这段代码
/**
* 取缩略图
*
* @access public
* @param Widget_Archie $widget
* @param mixed $size
* @param mixed $link
* @return String
**/
function getThumb($widget, $random = false, $size = null, $link = false){
$thumb = '';
preg_match_all( "/<[img|IMG].*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/", $widget->content, $matches );
$options = Typecho_Widget::widget('Widget_Options');
$attach = $widget->attachments(1)->attachment;
if (isset($attach->isImage) && $attach->isImage == 1){
//附件图
$thumb = $attach->url;
}elseif(isset($matches[1][0])){
//从内容正则
$thumb = $matches[1][0];
}
if(array_key_exists('thumb',unserialize($widget->fields))){
//thumb字段
$thumb = $widget->fields->thumb;
}
$thumb = empty($thumb) ? $options->default_thumb : $thumb; // 主题设置默认图片
$thumb = (empty($thumb) && $random) ? $options->themeUrl . '/img/thumbs/'.mt_rand(0,9).'.jpg' : $thumb; // 主题自带随机图片
if(empty($thumb))
return '';
if(!empty($options->src_add) && !empty($options->cdn_add))
$thumb = str_ireplace($options->src_add,$options->cdn_add,$thumb);
if($link){
return $thumb;
} else {
return '<img src="' . $thumb .'" />';
}
}
输出缩略图
在 index.php
加入以下代码就可以输出缩略图了
<div class="post-cover">
<a href="<?php $this->permalink() ?>">
<img class="thumb" src="<?php echo getThumb();?>">
</a>
</div>