Typecho自定义字段实现文章浏览次数统计
作者:鼠子丨Typecho · 暂无标签丨字数:1566 · 2024-05-29
最近我在开发ShuK-ON!主题时想加一个文章浏览次数统计的功能,以下代码即可实现;
代码放进functions.php,然后就可以在文章页通过输出统计次数。
function getViewsStr($widget, $format = "{views}") {
$fields = unserialize($widget->fields);
if (array_key_exists('views', $fields)) {
$views = (!empty($fields['views'])) ? intval($fields['views']) : 0;
} else {
$views = 0;
}
if ($widget->is('single')) {
$views = $views + 1;
$widget->setField('views', 'str', strval($views), $widget->cid);
}
return str_replace("{views}", $views, $format);
}
通过记录Cookies浏览过的文章,下次访问就不再统计
function getViewsStr($widget, $format = "{views}") {
$fields = unserialize($widget->fields);
if (array_key_exists('views', $fields)) {
$views = (!empty($fields['views'])) ? intval($fields['views']) : 0;
} else {
$views = 0;
}
if ($widget->is('single')) {
$vieweds = Typecho_Cookie::get('contents_viewed');
if (empty($vieweds)) {
$vieweds = array();
} else {
$vieweds = explode(',', $vieweds);
}
if (!in_array($widget->cid, $vieweds)) {
$views = $views + 1;
$widget->setField('views', 'str', strval($views), $widget->cid);
$vieweds[] = $widget->cid;
$vieweds = implode(',', $vieweds);
Typecho_Cookie::set("contents_viewed", $vieweds);
}
}
return str_replace("{views}", $views, $format);
}
comment
共有 0 条评论