文章次數統計是比較常用的功能,下面通過修改代碼實現統計。
控制台 / 外觀 / 編輯當前外觀 / 在 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 或者其他需要輸出閱讀量的位置調用即可。
最終效果如下。