6

【转载】Typecho缩略图实现方法,同时支持附件图片及网络/CDN图片

 3 years ago
source link: https://qq.md/posts/132
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【转载】Typecho缩略图实现方法,同时支持附件图片及网络/CDN图片

3天前 113℃ 0赞

网上流传着很多Typecho缩略图实现的方法,但是都不怎么样。

网上流传版本1缺陷:只能识别HTML模式下插入的图片,对于Markdown无效。

网上流传版本2缺陷:只能识别文章附件里面插入的图片,对于网络图片无效,使用七牛等图片CDN是块硬伤。 然后我就自己研制出另外一种新的办法,能同时识别文章附件图片和网络图片。

废话就不多说了,毕竟你也急了(^_^)

  • 1.到主题functions.php文件插入以下代码:
/** 输出文章缩略图 */ 
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/mr.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;
    }
}
  • 2.添加随机图片作为在文章无图时显示的默认缩略图:在主题img文件夹下新建random文件夹,依次放入1.jpg,2.jpg...~5.jpg,如果要更改随机图片的数量,或只想要一张默认的缩略图,请先按照注释修改好代码,然后在主题img文件夹放入random.jpg文件。图片可以自行到网上搜索下载。

  • 3.在主题文件夹下的index.php中对应位置加入

<?php showThumbnail($this); ?>
  • 4.然后就没有然后了。回到博客首页,缩略图是不是出来了呢?

转载自:泽泽社长 URL太长 就这样跳转吧!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK