Typecho非插件实现文章阅读次数统计

1710 阅读 暂无评论 69 字

网上很多Typecho文章阅读次数统计的代码,但是基本上不能实时增加阅读次数,这个应该是最完美的文章阅读次数实现方法了。

cookie版

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.' 次阅读';
}

非cookie版

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')) {
        
        $db->query($db->update('table.contents')
            ->rows(array('views' => (int)$exist+1))
            ->where('cid = ?', $cid));
        $exist = (int)$exist+1;
    }
    echo $exist == 0 ? '暂无阅读' : $exist.' 次阅读';
}

输出

<?php Postviews($this); ?>
文章评论 (0)
评论功能已被站长关闭
QQ咨询
QQ号码
979779692
微信咨询
微信二维码
在线咨询
微信咨询 QQ咨询
客服头像

截屏,微信识别二维码

微信号:itx2021

(点击微信号复制,添加好友)

微信号已复制,请打开微信添加好友!