为Typecho增加文章阅读次数统计功能

Gavin Wu 2019年07月29日 17:07 Typecho 1,483 Views

文章次数统计是比较常用的功能,插件一搜一堆,下面说说把这个功能集成到主题里的方法:
把下面这段代码放到主题文件functions.php中


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function Postviews($archive) {
    $db = Typecho_Db::get();
    $cid = $archive->cid;
    if (!array_key_exists('views', $db->fetchRow($db->select()->from('table.contents')))) {
        $db->query('ALTER TABLE `'.$db->getPrefix().'contents` ADD `views` INT(10) DEFAULT 0;');
    }
    $exist = $db->fetchRow($db->select('views')->from('table.contents')->where('cid = ?', $cid))['views'];
    if ($archive->is('single')) {
        $cookie = Typecho_Cookie::get('contents_views');
        $cookie = $cookie ? explode(',', $cookie) : array();
        if (!in_array($cid, $cookie)) {
            $db->query($db->update('table.contents')
                ->rows(array('views' => (int)$exist+1))
                ->where('cid = ?', $cid));
            $exist = (int)$exist+1;
            array_push($cookie, $cid);
            $cookie = implode(',', $cookie);
            Typecho_Cookie::set('contents_views', $cookie);
        }
    }
    echo $exist == 0 ? '暂无阅读' : $exist.' 次阅读';
}

然后在首页index.php、文章页post.php或者其他需要输出阅读量的位置调用“即可(文章页必须要调用,否则无法统计)。

文章评论2 条

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Top