为了在博文元数据(发表时间、分类、评论数)里增加被阅读次数的条目显示,在DeepSeek的指导下折腾了几个小时,记录如下:

一、思路变化

想法是在评论数前面加上图标和“x次阅读”,图标要与其它三个图标风格一致。起初在DeepSeek的建议下尝试直接在 SQLite 中给 contents 表加 views 字段,导致整站白屏报错。最终决定利用 Typecho 原生的“自定义字段(fields 表)”来存数据,彻底绕开了修改表结构带来的崩溃风险。并且把所有阅读数加起来可以大略作为博客总访问量显示在页脚。

二、最终版代码汇总

1. functions.php(核心逻辑)

修改原因:为了增加阅读次数显示,加入 views 自定义字段的自动调用;利用 table.fields 进行读写以避免 SQLite 兼容问题;加入 1 小时 Cookie 防刷,防止 F5 狂刷;加入全站总数求和以在页脚显示总访问量。

<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

function themeConfig($form) {
    // 原有配置项
    $logoUrl = new \Typecho\Widget\Helper\Form\Element\Text(
        'logoUrl', null, null, _t('网站 Logo'), _t('在这里填写图片 URL,网站将显示 Logo')
    );
    $form->addInput($logoUrl->addRule('url', _t('请填写正确的 URL 地址')));
    $colorSchema = new \Typecho\Widget\Helper\Form\Element\Select(
        'colorSchema', array(null => _t('自动'), 'light' => _t('浅色'), 'dark' => _t('深色'), 'customize' => _t('自定义')),
        null, _t('外观风格'), _t('如果选择了自定义,主题将使用 theme.css 的样式')
    );
    $form->addInput($colorSchema);
}

// 1. 自定义字段:让编辑器自动出现 views 输入框
function themeFields($layout) {
    $views = new \Typecho\Widget\Helper\Form\Element\Text(
        'views', null, '0', _t('阅读量'), _t('请在此填写数字,新文章建议填 0。代码会自动累加。')
    );
    $layout->addItem($views);
}

// 2. 文章阅读量:安全读写 fields 表 + Cookie 防刷
function getPostViews($archive) {
    if (!$archive->is('single')) {
        $views = $archive->fields->views;
        return $views ? (int)$views : 0;
    }
    $db = Typecho_Db::get();
    $cid = $archive->cid;
    $cookieName = 'typecho_views_' . $cid;
    $row = $db->fetchRow($db->select('str_value')->from('table.fields')
        ->where('cid = ?', $cid)->where('name = ?', 'views'));
    $views = $row ? (int)$row['str_value'] : 0;

    if (!isset($_COOKIE[$cookieName])) {
        $views++;
        if ($row) {
            $db->query($db->update('table.fields')
                ->rows(array('str_value' => (string)$views, 'int_value' => $views))
                ->where('cid = ?', $cid)->where('name = ?', 'views'));
        } else {
            $db->query($db->insert('table.fields')
                ->rows(array('cid' => $cid, 'name' => 'views', 'type' => 'str', 'str_value' => (string)$views, 'int_value' => $views)));
        }
        setcookie($cookieName, '1', time() + 3600, '/', '', false, true);
    }
    return $views;
}

// 3. 全站总访问量统计
function getAllViews() {
    $db = Typecho_Db::get();
    $row = $db->fetchRow($db->select(array('SUM(int_value)' => 'total_views'))->from('table.fields')->where('name = ?', 'views'));
    $total = $row ? (int)$row['total_views'] : 0;
    return number_format($total);
}

// 4. 页面 Meta 输出(含图标)——即文章下面的发表日期、分类、评论数,这里加上阅读次数
function postMeta(\Widget\Archive $archive, string $metaType = 'archive') {
?>
    <header class="entry-header text-center">
        <h1 class="entry-title" itemprop="name headline">
            <a href="<?php $archive->permalink() ?>" itemprop="url"><?php $archive->title() ?></a>
        </h1>
        <?php if ($metaType != 'page'): ?>
        <ul class="entry-meta list-inline text-muted">
            <li class="feather-calendar"><time datetime="<?php $archive->date('c'); ?>" itemprop="datePublished"><?php $archive->date(); ?></time></li>
            <li class="feather-folder"><?php $archive->category(', '); ?></li>
            <li class="feather-eye"><?php echo getPostViews($archive); ?> 次阅读</li>
            <li class="feather-message"><a href="<?php $archive->permalink() ?>#comments"  itemprop="discussionUrl"><?php $archive->commentsNum(_t('暂无评论'), _t('1 条评论'), _t('%d 条评论')); ?></a></li>
        </ul>
        <?php endif; ?>
    </header>
<?php
}

2. theme.css(样式补丁)

修改原因:为文章元数据的阅读次数指定图标。

/* 阅读量眼睛图标(路径适配自带“Classic 22”主题目录结构) */
.feather-eye:before {
    content: "";
    display: inline-block;
    margin-right: 0.25rem;
    background: url("./static/img/eye.svg") no-repeat center center/contain;
    width: 1rem;
    height: 1rem;
    vertical-align: text-top;
}

3. eye.svg(图标)

将以下代码存为eye.svg文件,放到“Classic 22”主题的static/img/目录下。

/* 阅读量眼睛图标(适配自带“Classic 22”主题风格) */
<svg
  xmlns="http://www.w3.org/2000/svg"
  width="24"
  height="24"
  viewBox="0 0 24 24"
  fill="none"
  stroke="#64748b"
  stroke-width="2"
  stroke-linecap="round"
  stroke-linejoin="round"
>
  <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
  <circle cx="12" cy="12" r="3" />
</svg>

4. footer.php(页脚显示访问量)

以“Classic 22”主题默认页脚代码为例,有好几条<li>,增加一条:

<li>访问量:<?php echo getAllViews(); ?> 次</li>

标签:无

你的评论