专注云服务商活动
网站运营运维笔记

Typecho程序调用文章缩略图的代码

如果我们有在使用Typecho二次开发主题功能可能需要用到调用内容图片作为缩略图。

/** 输出文章缩略图 laozuo.org */ 
function showThumbnail($widget)
{ 
    // 当文章无图片时的默认缩略图
    $rand = rand(1,5); // 随机 1-5 张缩略图
    $random = $widget->widget('Widget_Options')->themeUrl . '/img/sj/' . $rand . '.jpg'; // 随机缩略图路径
   // $random = $widget->widget('Widget_Options')->themeUrl . '/img/laozuo.jpg'; // 若只想要一张默认缩略图请删除本行开头的"//"

    $attach = $widget->attachments(1)->attachment;
    $pattern = '/\<img.*?src\=\"(.*?)\"[^>]*>/i'; 
    

if (preg_match_all($pattern, $widget->content, $thumbUrl)) {
         echo $thumbUrl[1][0];
    } else     if ($attach->isImage) {
      echo $attach->url; 
    } else {
        echo $random;
    }
}

添加功能代码到定义文件页面中,当然有需要修改默认图片的URL。以及准备五张随机图。

<?php%20showThumbnail($this);%20?>

调用图,如果没有缩略图会调用默认的。

投上你的一票
域名主机商优惠信息推送QQ群: 627775477 获取商家优惠推送,禁言。
赞(0)
未经允许不得转载:老左笔记 » Typecho程序调用文章缩略图的代码