非插件实现cookie版Typecho文章阅读次数统计功能

时间:2020-08-01   阅读:300

文章阅读次数是文章很重要的一个元素,通过它可以知道文章被访问的次数。博客吧前面介绍有Typecho浏览统计和热门文章调用插件TePostViews,通过该插件就可以实现统计每篇文章的阅读浏览次数。但是除了使用插件外,其实也可以直接在typecho主题中添加函数代码实现。此外下面分享的typecho阅读次数统计代码加入了cookie验证,重复刷新页面也只会增加一次阅读次数。

操作步骤:

在当前使用的typecho主题的functions.php文件中添加以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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'];}

在主题的post.php(文章内容页面)、index.php(列表页)或page.php(单页面)文件中添加阅读次数调用代码:

1
<?php get_post_view($this) ?>

效果可以看博客吧的Typecho Seven主题:https://www.boke8.net/teseven.html

代码来自https://qqdie.com/archives/typecho-read-statistics.html

文章由 博客吧 整理发布

上一篇:typecho导航栏调用分类目录

下一篇:Typecho更换空间出现“Database Server Error”错误

网友评论