MENU

Typecho Mirages 主题相邻文章默认头图去重

2021 年 06 月 19 日 • 阅读: 13599 • 博客

因为太懒,基本没有专门做过文章头图,只在设置里添加了几张默认图片,让主题随机挑选。后发现相邻文章会出现相同图片,观感不佳(虽然最终也不会很好),遂搜索代码予以更改。

代码逻辑在 /path/to/typecho/usr/themes/Mirages/lib/Content.php 文件的 loadDefaultThumbnailForArticle 函数:

public static function loadDefaultThumbnailForArticle($cid) {
    $defaultThumbs = self::exportThumbnails();
    $length = count($defaultThumbs);
    if ($length > 0) {
        $index = abs(intval($cid)) % count($length);
        $thumb = $defaultThumbs[$index];
    } else {
        $thumb = NULL;
    }
    return $thumb;
}

可以看到,作者根据文章 cid 对图片数量取余选取图片。尽管 cid 不同,运算后的结果也可能相同,这就可能导致上述问题。

简单起见,我直接让静态变量每次加 1,更改后的代码如下:

private static $defaultThumbs;
private static $defaultThumbsLength;
private static $nextThumbnailIndex; 

public static function loadDefaultThumbnailForArticle($cid) {
    if (self::$defaultThumbs == NULL) {
        // 这些变量存活于当前页
        self::$defaultThumbs = self::exportThumbnails();
        self::$defaultThumbsLength = count(self::$defaultThumbs);
        self::$nextThumbnailIndex = rand(0, abs(self::$defaultThumbsLength - 1));
    }
    if (self::$defaultThumbsLength > 0) {
        $index = self::$nextThumbnailIndex++ % self::$defaultThumbsLength;
        $thumb = self::$defaultThumbs[$index];
    } else {
        $thumb = NULL;
    }
    return $thumb;
}

文章默认图片的添加位置为 控制台 - 外观 - 设置外观 - 配图和图片管理 - 卡片式文章列表的默认背景图列表。现在刷新下主页,感觉稍微好了一点。

TG 大佬群 QQ 大佬群

返回文章列表 文章二维码
本页链接的二维码
打赏二维码
添加新评论

Loading captcha...

已有 1 条评论
  1. zizdog zizdog   Windows 10 x64 Edition  Google Chrome 96.0.4664.55

    脑洞决定一切,又是一个潜在的产品经理。