
编写 functions.php 中的代码(给出的图片地址是绝对地址,如果想要相对地址可以使用php操作字符串进行截断。)
function img_postthumb($cid) {
$db = Typecho_Db::get();
$rs = $db->fetchRow($db->select('table.contents.text')
->from('table.contents')
->where('table.contents.cid=?', $cid)
->order('table.contents.cid', Typecho_Db::SORT_ASC)
->limit(1));
preg_match_all("/\<img.*?src\=\"(.*?)\"[^>]*>/i", $rs['text'], $thumbUrl); //通过正则式获取图片地址
$img_src = $thumbUrl[1][0]; //将赋值给img_src
$img_counter = count($thumbUrl[0]); //一个src地址的计数器
switch ($img_counter > 0) {
case $allPics = 1:
echo $img_src; //当找到一个src地址的时候,输出缩略图
break;
default:
echo ""; //没找到(默认情况下),输出默认图片
};
}调用代码
<img src="<?php echo img_postthumb($this->cid); ?>"> <!--如果函数是输出的图片地址的话,则去掉上面注释实现插入图片-->
不过我嫌这个麻烦,而且不好控制,所以用的是调取附件,内容图片是直接通过编辑器上传,用的是ueditor,而附件是专门用作缩略图来使用,直接在需要调取缩略图的地方使用一下代码即可。
列表页使用代码
<?php if($this->attachments(1)->attachment->isImage) $this->attachments(1)->attachment->url(); ?>
内容页使用代码
<?php $this->attachments(1)->attachment->url(); ?>

评论已关闭