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?>

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


【AD】丽萨主机英国VPS推荐 英国原生IP双ISP家宅主机

【AD】美国洛杉矶/香港/日本VPS推荐,回程电信CN2 GIA线路,延迟低、稳定性高、免费备份_搬瓦工