Typecho文章浏览次数统计

介绍
一个cookie统计1次,不清空浏览器缓存不会增加次数,只有别人再访问才会增加

1. function.php 页面底部加入代码

function get_post_view($archive)
{
    $cid    = $archive->cid;
    $db     = Typecho_Db::get();
    $prefix = $db->getPrefix();
    if (!array_key_exists('views', $db->fetchRow($db->select()->from('table.contents')))) {
        $db->query('ALTER TABLE `' . $prefix . 'contents` ADD `views` INT(10) DEFAULT 0;');
        echo 0;
        return;
    }
    $row = $db->fetchRow($db->select('views')->from('table.contents')->where('cid = ?', $cid));
    if ($archive->is('single')) {
 $views = Typecho_Cookie::get('extend_contents_views');
        if(empty($views)){
            $views = array();
        }else{
            $views = explode(',', $views);
        }
if(!in_array($cid,$views)){
       $db->query($db->update('table.contents')->rows(array('views' => (int) $row['views'] + 1))->where('cid = ?', $cid));
array_push($views, $cid);
            $views = implode(',', $views);
            Typecho_Cookie::set('extend_contents_views', $views); //记录查看cookie
        }
    }
    echo $row['views'];
}

2. 在需要的地方引入代码

<?php get_post_view($this) ?>

在首页添加计数
打开文件: usr/themes/default/index.php
找到下面行:

<li itemprop="interactionCount"> <a itemprop="discussionUrl" href="<?php $this->permalink() ?>#comments"><?php $this->commentsNum('评论', '1 条评论', '%d 条评论'); ?></a></li> 

添加:

<li><span class="view-times"><?php get_post_view($this) ?>次浏览</span></li> 

在文章内容页添加计数
打开文件: usr/themes/default/index/post.php
找到下面行:

<li><?php _e('分类: '); ?><?php $this->category(','); ?></li>

在后面添加:

<li><span class="view-times"><?php get_post_view($this) ?>次浏览</span></li>