• 海阔天空 - Beyond
  • 过火 - 张信哲
Oo阿佳博客oO/

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

原文地址:https://www.seo135.com/seogo/311.html

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); ?>

留下一条评论

暂无评论

『阿佳博客』恭祝各位 迎龙年,送虎岁,祝福满溢在心间。愿新的一年里,你的生活如诗如画,精彩纷呈。愿你的事业如日中天,步步高升。祝你龙年快乐,吉祥如意!