有时候在实际开发项目中,我们需要判断后台是否设置有缩略图,如果没有就需要调用默认缩略图或者获取文章第一张图片作为缩略图。
下面我们来讲一下再ThinkCMF中如何获取文章第一张图片。
目标效果
设置有缩略图时,显示设置的缩略图
未设置缩略图时,提取文章第一张图片作为缩略图
未设置缩略图、且文章中没有图片时,显示默认缩略图。
自定义函数:cmf_first_image_url()
文件地址:./simplewind/cmf/common.php
/**
* 自定义函数
* 获取文章内容第一张图片,生成缩略图
*
*/
function cmf_get_first_image_url($id)
{
//根据ID查询文章正文内容
$content=Db::table('cmf_portal_post')->field('post_content')->where('id',$id)->find();
//将HTML实体转为自字符
$content['post_content']=html_entity_decode($content['post_content']);
//img路径的正则表达式
$pattern="/<[img|IMG].* src=[\'|\"](.* ( :[\.gif|\.jpg|\.png|\.jpeg]))[\'|\"].* [\/] >/";
//匹配IMG标签获得数组
preg_match_all ($pattern, $content['post_content'], $pat_array);
//判断$pat_array[1][0]为空,输出默认图片
if(isset($pat_array[1][0])){
$temp=$pat_array[1][0];
return $temp;
}else{
$temp= cmf_get_theme_path()."/public/assets/images/default_tupian1.png";
return $temp;
}
}
注:cmf_get_theme_path()函数获取模板路径。
模板中用法:
<if condition="empty($vo.more.thumbnail)">
<img src="{:cmf_get_first_image_url($vo['id'])}" class="img-responsive" alt="{$vo.post_title}" width="100%">
<else />
<img src="{:cmf_get_image_url($vo.more.thumbnail)}" alt="{$vo.post_title}" width="100%">
</if>
星之书笔记