Loading

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

文章次数统计是比较常用的功能,下面通过修改代码实现统计。

控制台 / 外观 / 编辑当前外观 / 在 functions.php 加入以下代码
代码已中加入了cookie验证,让文章浏览次数更具有真实性
阅读次数记录在 db._contents.views表中。

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;
}

调用方式 : <?php Postviews($this); ?>
文章页 post.php 必须要调用,否则无法统计。

然后在首页 index.php 或者其他需要输出阅读量的位置调用即可。

最终效果如下。

posted @ 2020-01-12 11:52  Outsrkem  阅读(1232)  评论(0编辑  收藏  举报